手撕shared_ptr智能指针
Posted 每天告诉自己要努力
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手撕shared_ptr智能指针相关的知识,希望对你有一定的参考价值。
#include <bits/stdc++.h>
using namespace std;
class control_block
private:
atomic<size_t> cnt;
public:
control_block() : cnt(0)
void add() cnt++;
void sub() cnt--;
size_t getCnt() return cnt;
;
template<class T>
class mySharedPtr
private:
T* m_ptr;
control_block* ctrl_blk;
void release()
if (ctrl_blk != nullptr)
ctrl_blk->sub();
if (ctrl_blk->getCnt() == 0)
delete m_ptr;
delete ctrl_blk;
m_ptr = nullptr;
ctrl_blk = nullptr;
public:
mySharedPtr() : m_ptr(nullptr), ctrl_blk(new control_block())
explicit mySharedPtr(T* ptr) : m_ptr(ptr)
ctrl_blk = new control_block();
ctrl_blk->add();
mySharedPtr(const mySharedPtr& ptr)
ctrl_blk = ptr.ctrl_blk;
m_ptr = ptr.m_ptr;
ctrl_blk->add();
mySharedPtr(mySharedPtr&& ptr)
m_ptr = ptr.m_ptr;
ctrl_blk = ptr.ctrl_blk;
ptr.m_ptr = nullptr;
ptr.ctrl_blk = nullptr;
mySharedPtr& operator=(const mySharedPtr& ptr)
if (this == &ptr) return *this;
release();
m_ptr = ptr.m_ptr;
ctrl_blk = ptr.ctrl_blk;
ctrl_blk->add();
return *this;
~mySharedPtr()
release();
T* operator->()
return m_ptr;
T& operator*()
return *m_ptr;
size_t use_count()
return ctrl_blk->getCnt();
;
int main ()
mySharedPtr<string> p1(new string("hello world"));
cout << *p1 << " " << p1.use_count() << endl;
mySharedPtr<string> p2(p1);
cout << *p2 << " " << p2.use_count() << endl;
mySharedPtr<string> p3(new string("hello"));
p2 = p3;
cout << *p2 << " " << p2.use_count() << endl; //hello 2
cout << *p1 << " " << p1.use_count() << endl; //hello world 1
system("pause");
return 0;
以上是关于手撕shared_ptr智能指针的主要内容,如果未能解决你的问题,请参考以下文章