C++ : share_ptr

发布时间:2019-06-23 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了C++ : share_ptr脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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

class child;

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

class child
{
public:
    ~child() { 
        std::cout <<"destroying childrenn"; 
    }
   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;   
}

脚本宝典总结

以上是脚本宝典为你收集整理的C++ : share_ptr全部内容,希望文章能够帮你解决C++ : share_ptr所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。