为什么指向同一内存的多个共享指针会导致内存泄漏? [英] Why would multiple shared pointers pointing to the same memory cause memory leak?

查看:35
本文介绍了为什么指向同一内存的多个共享指针会导致内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关共享指针的书,这本书说有多个共享指针指向同一个内存是个坏主意,因为如果一个shared_ptr引用计数减少为0,它将释放该内存,从而使另一个shared_ptr指向垃圾.

I am reading about shared pointers and the book say that it is bad idea having multiple shared pointers point to the same memory because if one shared_ptr reference count decrease to 0, it will deallocate that memory, making the other shared_ptr pointing to garbage.

int *z = new int;
shared_ptr<int> bad1(z); 
shared_ptr<int> bad2(z);

但是,当z的引用计数变为0时,shared_ptr都不都知道吗?

However, when the reference count for z becomes 0, wouldn't both shared_ptr know this?

推荐答案

那不会引起泄漏.实际上,情况要糟得多,因为您有两个指向同一内存的 unrelated 共享指针.这意味着双方都将认为自己拥有该内存的所有权,并且每个方都将尝试自己释放该内存.

That won't cause a leak. It's actually much worse, since you have two unrelated shared pointers pointing to the same memory. Which means both will think they have ownership of the memory, and each will try to free it on their own.

如果要使两个共享内存对象指向同一内存,请使用 std :: shared_ptr 初始化(或分配):

If you want two shared memory object pointing to the same memory, then use the std::shared_ptr initialization (or assignment):

shared_ptr<int> good1(new int);
shared_ptr<int> good2 = good1;

这篇关于为什么指向同一内存的多个共享指针会导致内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆