shared_ptr的缺陷:内存泄露

来源:互联网 发布:天下粮仓知乎 编辑:程序博客网 时间:2024/05/29 09:12
循环引用或者自引用容易造成内存泄露,可以使用weak_ptr避免
class CBase2;class CBase{public:CBase(int m = 0) : nValue(m){ cout << "CBase()" << endl; }~CBase(){ cout << "~CBase()" << endl; }int nValue;shared_ptr<CBase2> pt;};class CBase2{public:CBase2(int m = 0) : nValue(m){ cout << "CBase2()" << endl; }~CBase2(){ cout << "~CBase2()" << endl; }int nValue;shared_ptr<CBase> pt;};int main(){shared_ptr<CBase> p1(new CBase(5));shared_ptr<CBase2> p2(new CBase2(5));p1->pt = p2;p2->pt = p1;return 0;}

0 0