Where should we free the dynamic memory if we do a "new" in one of our methods ?

Hello,
If we request dynamic memory in the constructor of our class, we have to delete it in the destructor. But Where should we free the dynamic memory if we do a "new" in one of our methods ?

Cheers,
A.
You delete things when you don't need them any more. If, for example, you have a vector<int*> and your method pushes new int on it, delete the contents of that vector in the destructor. However if you have a single member int* and a method which assigns a new int to it, deleteing it only in the destructor would leak memory should you call that method more than once. In this case you should delete in the method:
1
2
3
4
5
6
7
8
9
struct S{
   int* i;
   S() : i(0) {}
   void method(){
      delete i;
      i = new int;
   }
   ~S(){ delete i; }
};

Note the constructor. deleteing an invalid pointer will end poorly, but deleteing a null pointer simply does nothing. (If you don't know what's with the :, google "initializer list". It's not necessary here though..)
Note the destructor. The method will only delete if called several times. You still need the destructor to delete the last instance.
Topic archived. No new replies allowed.