离开范围时不会调用析构函数 [英] Destructor not being called when leaving scope

查看:158
本文介绍了离开范围时不会调用析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C ++中的内存管理,我不知道为什么只有一些析构函数在调用范围时被调用。在下面的代码中,当myfunc结束时,只调用obj1析构函数,而不是动态分配的obj2。

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 ;

}

这里是析构函数:

cl1 :: ~cl1 () {

std::cout<< " cl1 destructor called"<<std::endl;
std::cout << this->data << std::endl; //just to identify the obj
delete [] str;
str = NULL ;

};


推荐答案

如果使用 new

obj2= new cl1;

然后除非你调用 delete 它的析构函数不会被隐式调用。

Then unless you call delete on it, its destructor won't be called implicitly.

编辑:作为@David,意见中的意见,可以明确地调用对象的析构函数,但在我的经验很少有需要手动调用析构函数,除非有人使用新版本的新版本。

As @David, meantions in comments, One may call destructor of an object explicitly but in my experience there is rarely a need to manually call the destructor unless one is using placement new version of new.

堆栈上的变量在范围结束时被隐式清除(通过调用它们的析构函数)。

Variables on stack are implicitly cleaned up(by calling their destructors) when their scope ends.

动态分配的对象不会被隐式清除,用户有责任清除它们,显式调用 delete

Dynamically allocated objects are not implicitly cleaned, it is the responsibility of the user to clean them up explicitly calling delete.

这是我们不应该使用原始指针,而是使用智能指针的原因。

This is the very reason one should not use raw pointers but use smart pointers.

这篇关于离开范围时不会调用析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆