Is it safe to self-assign a std::shared_ptr? So here is an example:
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;
I know that assigning a shared_ptr object:
So in this example the object is the same on both LHS and RHS and the ordering of these two RC changes inside the assignment operator is unspecified.
I don't really know what happens exactly in case of self assignment.
Per the cppreference docs on shared_ptr's operator= (emphasis added):
Replaces the managed object with the one managed by
r.If
*thisalready owns an object and it is the lastshared_ptrowning it, andris not the same as*this, the object is destroyed through the owned deleter.
Basically, they already thought of this possibility, and the implementation is required to handle this case; self-assignment does not delete the object, even if it's the only owner of the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With