-1

I'm trying to delete all object from my memory but I'm not sure what also to delete and whats the best way.

void createAss(Object& object) {
  Ass a1 = Ass("asdf");
  Ass a2 = Ass("aaa");

  object.addAss(a1);
  object.addAss(a2);
}

int main(void) {
  Object obj("header");

  createAss(obj);

  return 0;
}

So my main question is do I have to delete a1, a2 and obj within the main function or should it be done by the Destructor of the certain class?

Christophe
  • 68,716
  • 7
  • 72
  • 138
vicR
  • 789
  • 4
  • 23
  • 52

1 Answers1

1

At the end of main(), all its local objects are destroyed by their respective destructor. That's what happens automatically to obj. You do not need to delete anything, nor call the destructor. The compiler will take care.

THe question is related to the definition of Object and more precisely, the implementation of addAss() and of ~Object():

  • If addAss() uses new to create a copy of the object passed as argument, then ~Object() should of course delete them.

  • If you use some std containers, to store these objects, the destructor of the container will take care of the necessary destruction.

Remark:

Your statement Ass a1 = Ass("asdf"); is correct. But as you speak of delete I'd like to clarify that this statement does not create a pointer: You just create a local a1 object that is initialised with the contructor Ass("asdf"). It will be automatically destroyed when leaving createAss().

Christophe
  • 68,716
  • 7
  • 72
  • 138