-3

Does doing the following, create memory problems (new allocations without proper deletes) Assuming an object named "object"

class aClass
 { 
private:
    object* myobject;
public:
    aClass() : myobject(NULL) {};
    ~aClass() 
         {
            if(myobject)
               delete myobject;
             myobject = NULL;
         }
    void myfuction() 
       {
          if(myobject)
             myobject = new object();
       }
 }

does calling myfunction() often create memory which is never released, or the fact that i create the variable and copy it to myobject is safe, because at the end the myobject gets deleted ?

Sam Gomari
  • 733
  • 4
  • 13
  • 37

1 Answers1

2

does calling myfunction() often create memory which is never released,

Currently as this function is written, it would never allocate any memory at all, since you have (correctly) initialized the pointer in your constructor:

aClass() : myobject(NULL) {};
                 // ^^^^

so the condition in myfunction()

if(myobject)

will never be met, supposed the only code where memory allocation is done for myobject is in myfunction().

or the fact that i create the variable and copy it to myobject is safe, because at the end the myobject gets deleted ?

Well, calling delete for a NULL pointer is transparent and won't ever fail.


Actually I think you want to write myfunction() like this:

void myfuction() {
    if(!myobject)
    // ^ Check if myobject is NULL
         myobject = new object();
}

The destructor will correctly delete the allocated memory as soon the aClass instance goes out of scope.

But be aware of the Rule of Three and other operations that would affect assignments to the myobject member.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190