Why can I create an object of a class with private destructor on free store but not on the stack ?
For example this is illegal:
class Foo
{
public:
explicit Foo( int );
static void delete_foo(Foo* foo ) { delete foo; }
private:
int x;
~Foo();
Foo( const Foo& );
Foo& operator=(const Foo& );
};
int main()
{
Foo * fooptr = new Foo(5); // legal
Foo::delete_foo( fooptr ); // legal
Foo foo(5); // illegal
}
When you create it on the stack, it must be destroyed before the function can return. Presuming the function in question does not have access to the destructor, this is not allowed.
When you create it on the free store, it is left for other code, which has access to the destructor, to destroy it.
A member function of a class with a private destructor can create an instance on the stack. A static member function can even be called without a preexisting instance. There is probably no good reason to write such a thing, though.
Because an object with automatic storage* needs to be, well, automatically destructed. So the destructor needs to be available to call; if it's not, you can't have that type in automatic storage.
Contrarily, it's up to you to delete it when you allocate it dynamically. You can, of course, not do so.
*Objects here are, on "typical" platforms, commonly allocated on the stack.
Because creating an object on the free store doesn't require a public destructor, but creating it on the stack does because the objects will be destroyed when it goes out of scope. You can create the object on the free store, but you cannot delete it, so you'll have a memory leak unless the object or a friend function destroys it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With