Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 867
Sarp Kaya Avatar asked Jun 04 '13 01:06

Sarp Kaya


People also ask

Is delete calling destructor?

The answer is yes. Destructor for each object is called. On a related note, you should try to avoid using delete whenever possible.

Which is the difference between delete and delete in C Plus Plus?

3. What is the difference between delete and delete[] in C++? Explanation: delete is used to delete a single object initiated using new keyword whereas delete[] is used to delete a group of objects initiated with the new operator. 4.

Does destructor delete object?

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

Is delete called automatically in C++?

When an object goes out of scope normally, or a dynamically allocated object is explicitly deleted using the delete keyword, the class destructor is automatically called (if it exists) to do any necessary clean up before the object is removed from memory.


1 Answers

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.

like image 89
Sergey Kalinichenko Avatar answered Oct 07 '22 07:10

Sergey Kalinichenko