给自己分配一个 shared_ptr 安全吗?

Is assiging a shared_ptr to itself safe?

自行分配 std::shared_ptr 安全吗?所以这是一个例子:

std::shared_ptr<std::vector<std::string>> pVec = std::make_shared<std::vector<std::string>>();

std::cout << pVec.use_count() << std::endl; // 1
pVec = pVec;

我知道分配一个 shared_ptr 对象:

所以在这个例子中,对象在左轴和右轴上是相同的,并且这两个 RC 更改在赋值运算符内的顺序是未指定的。

我真的不知道在自我赋值的情况下到底会发生什么。

允许自赋值,内存泄漏是安全的。事实上,没有任何文档和 valgrind 测试表明共享指针的自我分配会产生内存泄漏。

根据 the cppreference docs on shared_ptr's operator=(强调已添加):

Replaces the managed object with the one managed by r.

If *this already owns an object and it is the last shared_ptr owning it, and r is not the same as *this, the object is destroyed through the owned deleter.

基本上他们已经想到了这种可能,需要执行才能处理这种情况;自我分配不会删除对象,即使它是对象的唯一所有者。