share_ptr 循环引用导致的内存泄露

class child;

class parent
{
public:
    ~parent() { 
        std::cout <<"destroying parent\n"; 
    }
    shared_ptr<child> cld;
};

class child
{
public:
    ~child() { 
        std::cout <<"destroying children\n"; 
    }
   shared_ptr<parent> prt;
};

意外延长对象的生命期

容器存放shared_ptr对象

vector<shared_ptr<int>> vec;
shared_ptr<int> p(new int(1));
vec.push_back(p);
cout << p.use_count() << endl; 
// print 2

Solution 1

vec.push_back(std::move(p));
cout << p.use_count() << endl;
// print 0

Solution 2

#include <boost/container/ptr_vector.hpp>
boost::ptr_vector<int> vec;
vec.push_back(new int(1));

//delete操作由ptr_vec完成

std::bind in C++11

void fun(shared_ptr<int>& p) {
    cout << p.use_count() << endl;
}

int main() {
    shared_ptr<int> p(new int(1));
    
    // p passed by value, not reference
    
    auto func = std::bind(fun, p); 
    func();
    // print 2
    return 0;
}

define custom destructor


class Base 
{
public:
   virtual ~Base() { cout << "Base "; }
};

class Derive : public Base 
{
public:
    ~Derive() { cout << "Derive "; }
};

void myDestructor(Base* b) {
    delete b;
    cout << "ok" << endl;
}
int main() {
    Base* bptr = new Derive();
    // can holder any kind of object
    shared_ptr<void> p(bptr, myDestructor); 
    /* print:
     * Derive Base ok
    */
    return 0;   
}

shiyang6017
158 声望59 粉丝