0

If every instance of a program has had its memory dynamically allocated using new , then it would be a good idea to deallocate them in the destructor.

#include <iostream>

using namespace std;


class c{


    public:

        c(){cout << "Created Object";}


    ~c(){
        delete this;
        cout << "Deleted object";
    }

};



int main(){


    c* ptr = new (nothrow) c();

    if(ptr == NULL){
        cout << "Null pointer" << endl;
        return 1;
    }

    delete ptr;
}

Is delete this simply not allowed?this points at a location in memory which had been allocated using new,so why would it cause a segmentation fault ? I know, the code is not generic for objects stored in stack but i am trying to figure out if there is a way to implement this concept.

zach
  • 95
  • 1
  • 7

3 Answers3

4

delete is not free. Let me cite cppreference on delete:

delete expression

If expression is not a null pointer ..., the delete expression invokes the destructor (if any) for the object that's being destroyed.

After that, whether or not an exception was thrown by any destructor, the delete expression invokes the deallocation function: either operator delete (for the first version of the expression) ...

So, delete this; inside ~c() will invoke ~c() and you'll end up with infinite recursion. In general, delete this; is allowed if you know what you're doing.

Community
  • 1
  • 1
Evg
  • 25,259
  • 5
  • 41
  • 83
1

delete this simply not allowed?

It is rarely useful, but it is allowed.

One case where it will never be useful is the destructor. Delete calls the destructor. If you call the destructor in the destructor which calls the destructor which calls the destructor which calls the destructor which calls the destructor which calls the destructor... There is a problem.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

delete ptr; deletes the object. In the destructor, delete this; deletes it a second time. That alone is a disaster, but as another answer mentions, that leads to the destructor being invoked a second time, so delete this; deletes the object a third time, which invokes the destructor, ad infinitum (or until stack overflow, whichever comes first).

Pete Becker
  • 74,985
  • 8
  • 76
  • 165