- 1、weak_par
- 2、弱智能指针的部分源码实现
弱智能指针
①不占用引用计数
②不能直接引用
③如果要用需要先转为强智能指针
void text01()
{
shared_ptr p(new int(10));
weak_ptrw_p(p);
cout << *p << endl;
cout << *(w_p.lock()) << endl;
}
int main()
{
text01();
return 0;
}
程序运行结果:
#pragma once #include "shared_ptr.h" templateclass Mweak_ptr { public: Mweak_ptr(Mshared_ptr& s_ptr) { _s_ptr = s_ptr; Mshared_ptr ::_count.insert(make_pair(_ptr, 1)); } Mshared_ptr lock() { if (Mshared_ptr ::_count.find(_s_ptr) != Mshared_ptr ::_count.end()) { return Mshared_ptr (_s_ptr); } return Mshared_ptr (); } private: T* _s_ptr; };



