在std::shared_ptr中使用=运算符时,上一个指针是否已销毁
Is previous pointer destroyed when using = operator in std::shared_ptr?
如果我用=运算符为std::shared_ptr分配一个新指针,上一个指针会自动被销毁(或取消引用)吗?
例如:
std::shared_ptr< Type > sp1 (ptr1, std::ptr_fun(destroy));
std::shared_ptr< Type > sp2 (ptr2);
sp1 = sp2; // now, will ptr1 be dereferenced and / or destroyed?
// and will the destroy() function get called?
是的,否则你会有一个漏洞,它会破坏拥有智能ptr的目的。
只是做了一个快速测试,我没有得到任何泄漏
#define BOOST_TEST_MODULE leakTest
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE( Leak_Test )
{
std::shared_ptr< int > sp1 (new int(3));
std::shared_ptr< int > sp2 (new int(4));
sp1 = sp2;
}
结果:
正在运行1个测试用例。。。
*未检测到错误按任意键继续。
是的。shared_ptr是一个数据结构,它有一个内部对象,它实际上保留了原始指针。这个内部对象有一个计数器,每次复制shared_ptr时该计数器都会递增,当shared_ptr被销毁或被分配另一个shared_ptt时该计数器会递减。一旦计数降到零,内部对象就会与原始指针一起被销毁。
在您的情况下:
std::shared_ptr< Type > sp1 (ptr1, std::ptr_fun(destroy)); //the counter of sp1 is 1
std::shared_ptr< Type > sp2 (ptr2); //the counter of sp2 is 1
sp1 = sp2; //the counter of sp1 is 0, the counter of sp2 is 2
因此,ptr1将被销毁,sp1和sp2将共享同一指针ptr2
相关文章:
- 修改函数中的指针(将另一个指针作为参数传递)
- 将指针分配给另一个指针时会发生什么情况?
- C++将一个指针分配给另一个指针时执行的类型检查
- 更改一个指针后更改乘法对象
- 如果我在 const 函数上使用指针,我可以返回什么?
- 从另一个指针指向函数的指针
- 什么相当于 Kotlin 上的C++指针?
- 有没有办法在同名类 (c++) 中为对象分配一个指针变量
- 无法删除堆内存上的指针
- 为什么通过定义另一个指针单元格,整个代码停止工作?
- C:试图将指针值复制到另一个指针中,得到可修改的左值错误
- 类模板上一个特定函数的未解析外部符号
- 在自定义构造函数中的堆上创建指针
- 错误:"int pow(double,int)"与上一个声明int pov(double a,int
- 如何获得GUID编码器,如果我在IMFTransform上有一个指针?
- 插入指针数组会删除上一个结果
- 在std::shared_ptr中使用=运算符时,上一个指针是否已销毁
- 如何在C++的链表中创建上一个指针
- Cinder:如何获得一个指针的数据帧生成,但从未显示在屏幕上
- 在堆栈上创建一个指针