在std::shared_ptr中使用=运算符时,上一个指针是否已销毁

Is previous pointer destroyed when using = operator in std::shared_ptr?

本文关键字:上一个 指针 运算符 是否 shared std ptr      更新时间:2023-10-16

如果我用=运算符为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