Sonic Atom
Sonic Atom

Reputation: 446

shared_ptr garbage collection when make_shared() is called multiple times

I'm aware that using smart pointers like std::shared_ptr adds garbage collection when the pointer goes out of scope, but I'm unclear as to whether the garbage collection also works if I call make_shared()multiple times on one shared_ptr.

For example:

std::shared_ptr<MyClass> mcPtr;

void assignment(int i)
{
  mcPtr = std::make_shared<MyClass>(i);
}

void main()
{
  assignment(5);

  // Some time later

  assignment(10);  // Does this cause a memory leak?
}

Upvotes: 1

Views: 1415

Answers (1)

NathanOliver
NathanOliver

Reputation: 180585

using a std::shared_ptr doesn't add garbage collection but when the shared pointer is destroyed at the end of the scope it is declared in it's destructor will be called. The destructor of the shared pointer handles releasing the memory.

Now when you call = std::shared_ptr::operator=() is called. From the standard 20.8.2.2.3.4

Effect: Equivalent to shared_ptr(std::move(r)).swap(*this)

So mcPtr is given the value of the new shared_ptr and the new shared_ptr gets the contents of mcPtr. Then the new shared_ptr goes out of scope, the destructor is called and the shared_ptr takes care of itself.

Upvotes: 2

Related Questions