-1

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.

Blubber
  • 1,375
  • 1
  • 15
  • 32

1 Answers1

0

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.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
  • Is there a way to do this if I used c++98? – Blubber Feb 04 '18 at 22:51
  • 1
    @Blubber Make design decisions on ownership and lifetime; this is not a coding issue but a design problem - how long should objects live for and who is responsible for them. `std::shared_ptr` is a simple answer to _"I don't know"_ but often the problem can be designed away. – Richard Critten Feb 04 '18 at 23:48
  • @RichardCritten: Exactly. In my experience, it's rare that `std::shared_ptr` is really the implementation of a robust design, especially since `std::unique_ptr` came along. – Christian Hackl Feb 05 '18 at 06:34