Proper lifecycle management of objects in C ++

I have some simple C ++ classes containing data. They are hierarchical, each of them contains a list of pointers to children (since I have a lot of them in my memory, I did not want to copy them).

I work only at the highest level (I pass it on to functions) and I would like the destructor at every level to destroy my children, so all I need to do is release all of them, this remove the call at the top of the main parent, This causes a problem when some classes are created on the stack, but this is really just a symptom of the problem.

As I see it, I need to create and destroy objects at the same level and, therefore, know whether I should call delete or not. However, this will force me to hold pointers to all children and destroy them after each use in my code, a dirtier solution than calling delete at the top of the main parent.

So my options are:

  • Never define them on the stack (BAD)
  • Pass a bool in the constructor indicating whether this object should be deleted or not (BAD)
  • Delete objects manually after each use, depending on how I created them (BAD)
  • Copy items locally (BAD if there can be many thousands)
  • Smart pointers? Some framework? (I'm pretty limited in what I can use)

Did I miss something? Any other ideas?

Thank you, Vadim.

+4
source share
2 answers

In C ++ 11, you must define a move constructor and call std::move on the object before it goes out of scope so that it can transfer ownership of resources that would otherwise delete d.

In C ++ 03, the same functionality can be defined without language formalism, but you need to add the state of the object where it is empty. This is often done by introducing a default constructor and implementing swap .

Pointers that are deleted must have a default value of null, and after swap (or the copy constructor or any other function) passes the pointers to a new container object that will go beyond the scope, they will get a NULL value. therefore delete has no effect (and makes the object unusable, which is dirty, but not so bad, as you can easily ensure that the object is not used for anything after moving it).

0
source

Consider storing child objects in std::list . Instead of using new you write a function that creates a new child using push_back() and returns a pointer to it. You will not need to kill children directly, and you will prevent leaks.

0
source

All Articles