Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is assiging a shared_ptr to itself safe?

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.

like image 355
Itachi Uchiwa Avatar asked Oct 29 '25 17:10

Itachi Uchiwa


1 Answers

Per the cppreference docs on shared_ptr's operator= (emphasis added):

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.

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.

like image 109
ShadowRanger Avatar answered Oct 31 '25 06:10

ShadowRanger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!