std::shared_ptr: reset() vs. assignment

AlwaysLearning picture AlwaysLearning · Jul 15, 2015 · Viewed 24.7k times · Source

This is a basic question, but I did not find a previous post about it. The title of the following question sounds like it might be the same question as mine, but the question itself does not match the title: is it better to use shared_ptr.reset or operator =?

I am confused about the purpose of the reset() member function of std::shared_ptr: what does it contribute in addition to the assignment operator?

To be concrete, given the definition:

auto p = std::make_shared<int>(1);
  1. Are the following two lines equivalent:

    p = std::make_shared<int>(5);
    p.reset(new int(5));
    
  2. What about these:

    p = nullptr;
    p.reset();
    

If the two lines are equivalent in both cases, then what is the purpose of reset()?


EDIT: Let me re-phrase the question to better emphasize its point. The question is: is there a case where reset() lets us achieve something that is not as easily achievable without it?

Answer

NathanOliver picture NathanOliver · Jul 15, 2015

When using reset() the parameter passed to reset need not be a managed object (nor can it be); whereas with = the right hand side must be a managed object.

So these two lines give you the same end result:

p = std::make_shared<int>(5); // assign to a newly created shared pointer
p.reset(new int(5)); // take control of a newly created pointer

But we cannot do:

p = new int(5); // compiler error no suitable overload
p.reset(std::make_shared<int>(5).get()); // uh oh undefined behavior

Without reset() you would not be able to reassign a shared pointer to a different raw pointer without creating a shared pointer and assigning it. Without = you wouldn't be able to make a shared pointer point to another shared pointer.