首页 > 代码库 > weak_ptr

weak_ptr

#include <iostream>
#include <memory>

using namespace std;

int main(int argc, char **argv)
{
//    shared_ptr<int> sp(new int(10));
    shared_ptr<int> sp = make_shared<int>(10);
    cout << sp.use_count() << " " << *sp << endl;
    shared_ptr<int> sp2 = sp;
    cout << sp2.use_count() << " " << *sp2 << endl;
    sp2.reset();
    cout << sp.use_count() << " " << *sp << endl;
    
    weak_ptr<int> wp = sp;
    cout << wp.use_count() << " " << endl;
    sp2 = wp.lock();
    cout << sp2.use_count() << " " << *sp2 << endl;
    
    sp.reset();
    cout << wp.use_count() << " " << wp.expired() << endl;
    sp2.reset();
    cout << wp.use_count() << " " << wp.expired() << endl;
}

技术分享

参考资料:

[内存管理]智能指针的好帮手weak_ptr

weak_ptr