14

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;
}
Unihedron
  • 10,902
  • 13
  • 62
  • 72
Sarp Kaya
  • 3,686
  • 21
  • 64
  • 103
  • You should never have a reason to call a destructor explicitly except for a few situations in which you'll know you need to. – chris Jun 04 '13 at 02:09
  • @chris Such as working around the lack of a placement delete: http://stackoverflow.com/questions/6783993/placement-new-and-delete – Scott Jones Jun 04 '13 at 03:02
  • @ScottJones, Exactly. – chris Jun 04 '13 at 03:04
  • A similar situation happened to me. I had two pointers, ptr1 and ptr2, pointing to the same memory location on the heap. I used ptr1 to call destructor explicitly but then I could access to that location with ptr2. but when I used delete on ptr1, I could no longer access with ptr2 to my object. – soheil_ptr Sep 03 '14 at 16:26

2 Answers2

24

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • What do you mean by "releases resources owned by the object"? Things like files, locks? – heretoinfinity Sep 03 '21 at 23:42
  • 1
    @heretoinfinity in most cases it's dynamically-allocated memory for storing things outside of the object itself, but files and locks are excellent examples, too. – Sergey Kalinichenko Sep 04 '21 at 02:28
  • I am somewhat confused and need clarity. By "second snippet" in your answer, do you mean the line with `delete foo;` or `foo->~Foo();`? Does the destructor `foo->~Foo()` not free up memory and since the destructor has the `delete` statement? – heretoinfinity Sep 06 '21 at 11:16
  • 1
    @heretoinfinity `foo->~Foo()` does not free up the dynamic memory for the object itself. It does free up the memory for `str`. – Sergey Kalinichenko Sep 06 '21 at 13:59
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.