智能指针weak_ptr使用
weak_ptr 的作用就是为了解决 shared_ptr 循环引用的问题,原理是对于shared_ptr 的指针采用只引用不计数的方法。
weak_ptr 的初始化只能是 weak_ptr 和 shared_ptr 的类型数据。
weak_ptr 使用之前需要做安全检测,expired() 判断是否有效,返回类型为bool值
lock返回值是一个 shared_ptr,如果内存已经被释放了,则会返回一个null。
#include<iostream> #include<memory> using namespace std; class A { private: int a; int b; public: A(){}; A(int a, int b):a(a), b(b){}; int get_a() { return a; }; int get_b() { return b; } void set_a(int val) { a = val; } void set_b(int val) { b = val; } }; int main() { shared_ptr<A> pa(new A()); shared_ptr<A> pb = make_shared<class A>(1,2); pa->set_a(3); cout << pa->get_a() << endl; //3 cout << pa->get_b() << endl; //0 cout << pb->get_a() << endl; //1 cout << pb->get_b() << endl; //2 cout << pa.use_count() << endl; //1 weak_ptr<A> wa = pa; cout << wa.use_count() << endl; //1 cout << pa.use_count() << endl; //1 cout << wa.lock()->get_a() << endl; //3 cout << wa.use_count() << endl; //1 cout << pa.use_count() << endl; //1 auto p = wa.lock(); cout << p->get_b() << endl; // 0 cout << wa.use_count() << endl; //2 cout << pa.use_count() << endl; //2 weak_ptr<A> wb(pb); pb.reset(); if (wb.lock() == nullptr) { cout << "pb is expired" << endl; } else { cout << wb.lock()->get_a() << endl; } pa.reset(); if (wa.expired()) { cout << wa.lock()->get_a() << endl; } else { cout << "pa is expired" << endl; } return 0; }