Destructor not being called when leaving scope

2019-02-11 07:01发布

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 ;

};

8条回答
淡お忘
2楼-- · 2019-02-11 07:38

obj2 -> ~cl1 ;

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 the delete 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.

查看更多
贼婆χ
3楼-- · 2019-02-11 07:46

First of all you should use delete operator to destrory an object and not call its destructor directtly. Secondly, by doing new 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 fo delete objj2; to delete the object.

查看更多
登录 后发表回答