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:
- will decrement the left hand side (LHS) operand reference count (RC), and then will check whether it is 0 (these previous operations are done atomically) and if so release the resource;
- also, will increment the right hand side (RHS) RC.
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.