c++ weak_ptr 和shared_ptr的用法

https://en.cppreference.com/w/cpp/memory/weak_ptr描述的很清楚,不会因为weak_ptr的存在,更改原有shared_ptr的生命周期,所以weak_ptr指向的shared_ptr析构后,weak_ptr就无法访问其所指的内容。
std::weak_ptr is a smart pointer that holds a non-owning (“weak”) reference to an object that is managed by std::shared_ptr.It must be converted to std::shared_ptr in order to access the referenced object.

而shared_ptr会因为赋值一次,reference count+1,只有当reference count为0时,内存才会回收。这就造成shared_ptr有循环引用的问题。

可以通过下列示例,加深理解。
----weak pointer ---------
#include
#include
#include
using namespace std;

class B;
class A
{
public:
weak_ptr _b;
A() { cout << “A()” << endl; }
~A() { cout << “~A()” << endl; }
int a = 10;
};

class B
{
public:
weak_ptr _a;
B() { cout << “B()” << endl; }
~B() { cout << “~B()” << endl; }
int b = 11;
};
shared_ptr pb ;
void fun2()
{
{
shared_ptr
pa = make_shared();
pb = make_shared();

pa->_b = pb;
pb->_a = pa;

auto wb = pa->_b.lock();
cout<b<_a.lock();
cout<a<_a.lock())
    cout<<"eee"<a<

}
int main()
{
fun2();
return 0;
}

output:
A()
B()
11
10
~A()
dddd
~B()

--------------shared ptr-----------------------

#include
#include
#include
using namespace std;

class B;
class A
{
public:
shared_ptr _b;
A() { cout << “A()” << endl; }
~A() { cout << “~A()” << endl; }
int a = 10;
};

class B
{
public:
shared_ptr _a;
B() { cout << “B()” << endl; }
~B() { cout << “~B()” << endl; }
int b = 11;
};
shared_ptr pb ;
void fun2()
{
{
shared_ptr
pa = make_shared();
pb = make_shared();

pa->_b = pb;
pb->_a = pa;

//auto wb = pa->_b.lock();
cout<b<_a.lock();
cout<a<_a.lock())
    cout<<"eee"<_a->a<

}
int main()
{
fun2();
return 0;
}

output: 没有析构A和B,所以有环形引用导致的内存泄露
A()
B()
11
10
eee10
dddd

你可能感兴趣的:(c++,c++,开发语言)