I am learning memory management in C++ and I don't get the why only some of the destructors are called when leaving scope. In the code below, only obj1 destructor is called when myfunc ends, not for the dynamically allocated obj2.
int myfunc (cl1 *oarg) {
cout << "myfunc called" << std::endl;
cl1 obj1(222,"NY");
cl1 *obj2;
obj2= new cl1;
oarg->disp();
obj2 -> ~cl1 ;
}
Here is the destructor I have :
cl1 :: ~cl1 () {
std::cout<< " cl1 destructor called"<<std::endl;
std::cout << this->data << std::endl; //just to identify the obj
delete [] str;
str = NULL ;
};
Don't do this! Use
delete obj2;
instead.Addendum
What you were trying to do was to call the destructor explicitly. Your code does not do that. Your code is getting the address of the destructor and then dropping it into the bit bucket. Your code is a no-op. The correct way to explicitly call the destructor is
obj2->~cli();
.Explicitly calling the destructor is usually something you should not do.
What you should do is to delete the memory created by
new
. The correct way to do that is to use thedelete
operator. This automatically calls the destructor and releases the memory. The destructor does not release the memory. Failing to use delete results in a memory leak.First of all you should use
delete
operator to destrory an object and not call its destructor directtly. Secondly, by doingnew
you are telling the compiler that you dont want to delete the object when it goes out of the scope. In such case you need to explictly fodelete objj2;
to delete the object.