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 <bits/stdc++.h>
#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<<wb->b<<endl;

auto wa = pb->_a.lock();
cout<<wa->a<<endl;
}

if(auto wa = pb->_a.lock())
    cout<<"eee"<<wa->a<<endl;

cout<<"dddd"<<endl;

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

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

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

#include <bits/stdc++.h>
#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<<pb->b<<endl;

//auto wa = pb->_a.lock();
cout<<pa->a<<endl;
}

//if(auto wa = pb->_a.lock())
    cout<<"eee"<<pb->_a->a<<endl;

cout<<"dddd"<<endl;

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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值