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.