shared_ptr陷阱

shared_ptr陷阱分析

慎用裸指针

	int* i1 = new int(100);

	//使用裸指针初始化多个shared_ptr会导致这多个shared_ptr之间没有关联,最终导致多次释放内存
	shared_ptr<int> sp1(i1);
	shared_ptr<int> sp2(i1);

	cout << sp1.use_count() << endl;  //打印1
	cout << sp2.use_count() << endl;  //打印
	//这段程序如果执行完,会出错,如果想要观测打印结果,使用断点调试

慎用get()返回的指针

  • 不能自己delete get() 返回的指针
  • 不能将get()返回的指针关联到其它智能指针(防止出现1.1中的问题)

不要将类中的this指针直接关联到其它shared_ptr

#include <iostream>
using namespace std;

//class A
//{
//public:
//	shared_ptr<A> getPoint()
//	{
//		return shared_ptr<A>(this);  //使用裸指针关联其它shared_ptr指针会导致内存多次释放的问题
//										 //解决办法:继承 enable_shared_from_this 模板
//	}
//};


class A:public enable_shared_from_this<A>
{
public:
	shared_ptr<A> getPoint()
	{
		return shared_from_this();
	}
};


int main()
{
	shared_ptr<A> sp(new A());

	shared_ptr<A> sp1 = sp->getPoint();

	return 0;
}

shared_ptr循环引用导致内存泄露

参考博客:https://www.cnblogs.com/douzujun/p/10803365.html

补充建议:尽量使用make_shared()函数构造shared_ptr指针

发布了123 篇原创文章 · 获赞 31 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_40794602/article/details/99619906