What is the difference between delete and calling

2019-02-10 11:05发布

问题:

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.