Search code examples
c++pointersmoveshared-ptrmove-semantics

Assigning a shared_ptr to another after calling get


shared_ptr<std::string> shared_ptr1 = std::make_shared<std::string>("Foo");
shared_ptr<std::string> shared_ptr2 = std::make_shared<std::string>("Bar"); 

std::string* normal_ptr = shared_ptr1.get(); 
shared_ptr1 = shared_ptr2; 

Now, will the first string "Foo" be garbage collected after the "shared_ptr1 = shared_ptr2" assignment? According to this , "Foo" isn't garbage collected. But I just want to make sure that what I am encountering isn't an undefined behavior.

Thank you!


Solution

  • Now, will the first string "Foo" be garbage collected after the "shared_ptr1 = shared_ptr2" assignment?*

    If you mean will the string that was allocated by std::make_shared<std::string>("Foo") be destroyed, then yes.

    That means that normal_ptr, after you do shared_ptr1 = shared_ptr2; points to an object that no longer exists.