Itachi Uchiwa
Itachi Uchiwa

Reputation: 3164

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:

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.

Upvotes: 3

Views: 1099

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155506

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.

Upvotes: 3

Zig Razor
Zig Razor

Reputation: 3525

The self assignment is allowed and it is safe speaking about memory leak. In fact no documentation and test with valgrind show that self assignment of shared pointers to themself produce memory leak.

Upvotes: 1

Related Questions