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 try
Why would the destructor be called while creating an instance of
MyClass
?
It isn't. It must be invoked automatically when the instance goes out of scope, though. If it's private, the compiler must not generate that code, hence the error.
If you think making the destructor private is obscure, another way to restrict a class to dynamic allocation is to make all the constructors private and only have MyClass::create()
functions returning dynamically allocated objects:
class MyClass {
public:
static MyClass* create() {return new MyClass();}
static MyClass* create(const Foo& f) {return new MyClass(f);}
private:
MyClass();
MyClass(const Foo&);
};
Note that returning naked pointers to objects that must be deleted is frowned upon. You should return smart pointers instead:
class MyClass {
public:
static std::shared_ptr create() {return new MyClass();}
static std::shared_ptr create(const Foo& f) {return new MyClass(f);}
// ...
};