C ++:为什么不调用析构函数? [英] C++: why it doesn't call a destructor?

查看:144
本文介绍了C ++:为什么不调用析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中使用了多余的括号。我以为本地变量作用域结束后何时应该调用析构函数,但它不能像这样工作:

I use extra brackets in my code. I thought when the destructor should be called after the local variable scope is ended but it doesn't work like this:

class TestClass {
public:
    TestClass() {
        printf( "TestClass()\n" );
    }
    ~TestClass() {
        printf( "~TestClass()\n" );
    }
};

int main() {
    int a, b, c;
    {
         TestClass *test = new TestClass();
    }
}

输出:


TestClass()

TestClass()

所以它不调用TestClass但是为什么呢?如果我手动调用它(删除测试),它将调用析构函数。但是为什么在第一种情况下不调用析构函数呢?

So it doesn't call the destructor of the TestClass but why? If I call it manually (delete test) it calls the destructor, right. But why it doesn't call the destructor in the first case?

推荐答案

TestClass *test = new TestClass();

您使用 new 创建了一个动态分配的对象(最有可能放在堆上)。这种类型的资源需要由您手动进行管理。通过管理,使用完后,应在其上使用 delete

You using new which creates a dynamically allocated object (most likely placed on the heap). This type of resource needs to be manually managed by you. By managing, you should use delete on it after you have done using it.

{
     TestClass *test = new TestClass();
     // do something
     delete test;
}

但是对于大多数目的和意图,您只需要使用自动-存储对象,这使您不必手动管理对象。它还最有可能具有更好的性能,尤其是在寿命短的对象中。 您应该始终喜欢使用它们,除非您确实有很好的理由不这样做。

But for the most of your purposes and intents, you just have to use automatic-storage objects, which frees you the hassle of having to manually manage the object. It would also most likely to have better performance especially in short-lived objects. You should always prefer to use them unless you have a really good reason not to do so.

{
     TestClass test;
     // do something
}

但是,如果您需要对于动态分配的对象或指针的对象,最好使用某种机制为您封装对象/资源的删除/释放,这也将为您提供额外的安全性,尤其是在使用异常和条件分支时。就您而言,最好使用 std ::

However, if you need the semantics of dynamically allocated objects or that of pointers, it will always be better to use some mechanism to encapsulate the deletion/freeing of the object/resource for you, which also provides you additional safety especially when you are using exceptions and conditional branches. In your case, it would be better if you use std::unique_ptr.

{
     std::unique_ptr<TestClass> test(new TestClass());
     // auto test = std::make_unique<TestClass>();  in C++14

     // do something (maybe you want to pass ownership of the pointer)
}



以下是一个相关链接,可帮助您决定使用自动存储对象还是动态分配的对象:
为什么C ++程序员应尽量减少对 new的使用?

这篇关于C ++:为什么不调用析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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