shared_ptr模拟代码。
#include //#include #include using namespace std; template class shared_ptr { T* m_ptr = NULL; int* m_inf = NULL; shared_ptr(){} public: shared_ptr(T* ptr) { m_inf = new int; *m_inf = 1; m_ptr = ptr; } shared_ptr(const shared_ptr& from) { deconstruct(); m_inf = from.m_inf; m_ptr = from.m_ptr; (*m_inf)++; } shared_ptr& operator=(const shared_ptr& from) { deconstruct(); m_inf = from.m_inf; m_ptr = from.m_ptr; (*m_inf)++; } ~shared_ptr() { deconstruct(); } void deconstruct() { if(m_inf != NULL) { (*m_inf)--; if(*m_inf == 0) { delete m_ptr; delete m_inf; m_ptr = NULL; m_inf = NULL; } } } T* operator->() { return m_ptr; } int use_count() { return *m_inf; } }; template static shared_ptr make_shared(int val) { return shared_ptr(new T(val)); } class A { int m_v; public: A(int v) { cout << "new: " << (m_v = v) << endl; } ~A() { cout << "delete: " << m_v << endl; } void DisPlay() { cout << "display " << m_v << endl; } }; shared_ptr TestSharePtr() { auto p = make_shared(123); cout << p.use_count() << endl; auto p2 = p; cout << p.use_count() << endl; // p2 = make_shared(456); cout << p.use_count() << endl; return p; } int main() { auto rst = TestSharePtr(); cout << "after call" << endl; rst->DisPlay(); return 0; }
关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心
版权所有: 红黑联盟--致力于做实用的IT技术学习网站