Or is it not possible, and I have to do a deep copy. Lets say I have an object A
, and I want to make a shallow copy of A
into B
. If I delete A
, and A
destroys all if its members, then B
would have dangling pointers. If A
doesn't destroy its members, then B
's pointers are still good. However, if I delete B
, then its members won't be destroyed when B
gets destroyed, so I will leak memory. Is there a way for an object to know when it has the only reference to memory, and delete it? Or is this not possible, and I have to use a deep copy.
Is there a way for an object to know when it has the only reference to memory, and delete it?
Yes, it's called std::shared_ptr
.