0

I have some classes that accept pointers to instances of other classes as arguments and stores them in their private members. If in the client code I create objects of all types on the stack, when the main returns they auto destruct and program works just fine. But if I create the same objects on the heap, I should delete the pointers to those objects in the destructors of the class(es) and again program executes fine. However, if I keep the changes and create objects on the stack again, there is memory corruption because of double delete. How can I make my classes destroy the pointers in either case without modifying the main client code?

Hamed
  • 36
  • 5
  • 2
    `I should delete the pointers to those objects in the destructors of the class(es)` no, only creator of the object should delete it – Iłya Bursov Apr 23 '20 at 19:32
  • 3
    in general - don't use raw pointers in c++, use smart ones, like std::shared_ptr – Iłya Bursov Apr 23 '20 at 19:33
  • Helpful reading; [What is ownership of resources or pointers?](https://stackoverflow.com/questions/49024982/what-is-ownership-of-resources-or-pointers) – user4581301 Apr 23 '20 at 20:26

0 Answers0