I know there are methods to prevent a class from being created on the heap, by preventing the user from using the new and delete operator. I am trying to do just the opposite. I have a class that I want to prevent the user from creating an instance of it on the stack, and that only instances instigated using the new operator will compile. More specifically, I want the following code to receive an error during compilation:
MyClass c1; //compilation error
MyClass* c1 = new MyClass(); //compiles okay
From searching the web, I found this suggestion on how to do it:
class MyClass {
public:
MyClass();
private:
void destroy() const { delete this; }
...
private:
~MyClass();
};
int main(int argc,char** argv)
{
MyClass myclass; // <--- error, private destructor called here !!!
MyClass* myclass_ptr = new MyClass;
myclass_ptr->destroy();
}
What i don't understand is why this should work. Why would the destructor be called while creating an instance of MyClass?