What is the difference between delete and calling destructor in C++

一世执手 提交于 2019-11-30 13:25:48

问题


As stated in the title, here is my code:

class Foo {

    public:
        Foo (int charSize) {
            str = new char[charSize];
        }
        ~Foo () {
            delete[] str;
        }
    private:
        char * str;
};

For this class what would be the difference between:

int main () {
    Foo* foo = new Foo(10);
    delete foo;
    return 0;
}

and

int main () {
    Foo* foo = new Foo(10);
    foo->~Foo();
    return 0;
}

回答1:


Calling a destructor releases the resources owned by the object, but it does not release the memory allocated to the object itself. The second code snippet has a memory leak.




回答2:


Whenever a call to destructor is made , the allocated memory to the object is not released but the object is no longer accessible in the program. But delete completely removes the object from memory.



来源:https://stackoverflow.com/questions/16908650/what-is-the-difference-between-delete-and-calling-destructor-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!