c++ - 未调用析构函数

标签 c++

根据:http://www.cplusplus.com/doc/tutorial/classes/

析构函数实现与构造函数相反的功能。当一个对象被销毁时,它会被自动调用,因为它的存在范围已经结束(例如,如果它被定义为函数中的局部对象并且函数结束)或者因为它是一个动态分配的对象并被释放使用运算符删除。

示例代码:

    class Something
    {
    public:
        Something() {cout << "construction called" << endl; }
        ~Something()    { cout << "destruction called" << endl; }
    };


    void foo(){
        Something *ob = new Something();
    }

    int _tmain(int argc, _TCHAR* argv[])
    {
        foo();
    }

最佳答案

确实如此,但是您在动态内存 中分配对象,这意味着它不会被破坏,直到您调用delete

because it is an object dynamically assigned and it is released using the operator delete.

你永远不会调用 delete。因此内存泄漏和未调用的析构函数:

void foo(){
    Something *ob = new Something();
    delete ob;
}

要么这样,要么简单地在自动内存中分配对象:

void foo(){
    Something ob;
}

或者将内存管理委托(delegate)给智能指针。

关于c++ - 未调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12587774/

相关文章:

c++ - Neon 指令,vsub_f32(a, b),是 a-b 还是 b-a?

c++ - 客户端的堆排序 vector ,错误地传递迭代器?

c++ - 无法使用 vector::插入 "no instance of overloaded function..."

c++ - 如何在 Visual Studio (C++) 中找到应用程序的入口点

c++ - 模板类 : ctor against function -> new C++ standard

c++ - 递归函数中的boost regex smatch表现得像一个静态变量

c++ qt 将图像添加到匿名标签(或其他小部件)

c++ - 为什么在使用其他库时会出现 LNK4098 冲突 - 尝试在 MSVS2010 Express 中编译 C++ 时?

c++ - clang 与 gcc CRTP : constexpr variable cannot have non-literal type

c++ - 在 C++ 中使用正则表达式查找 [/和 ] 之间的数字