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!
normal_ptrbecoming invalid after the assignmentshared_ptr1 = shared_ptr2?std::shared_ptrcan be seen as C++'s way of supporting reference counting. Reference counting is a valid form of garbage collection. I believe the view point thatstd::shared_ptris a form of garbage collection to be fair.shared_ptris a shared object, with a lifetime as long as its longest-lived owner. Reference-counting is the (rather obvious) implementation mechanism supporting shared ownership, not the other way around.