给自己分配一个 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
对象:
- 将递减左侧 (LHS) 操作数引用计数 (RC),然后检查它是否为 0(这些先前的操作是自动完成的),如果是则释放资源;
- 另外,将增加右侧 (RHS) RC。
所以在这个例子中,对象在左轴和右轴上是相同的,并且这两个 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.
基本上他们已经想到了这种可能,需要执行才能处理这种情况;自我分配不会删除对象,即使它是对象的唯一所有者。
自行分配 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
对象:
- 将递减左侧 (LHS) 操作数引用计数 (RC),然后检查它是否为 0(这些先前的操作是自动完成的),如果是则释放资源;
- 另外,将增加右侧 (RHS) RC。
所以在这个例子中,对象在左轴和右轴上是相同的,并且这两个 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 lastshared_ptr
owning it, andr
is not the same as*this
, the object is destroyed through the owned deleter.
基本上他们已经想到了这种可能,需要执行才能处理这种情况;自我分配不会删除对象,即使它是对象的唯一所有者。