Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private destructor

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
}
like image 735
There is nothing we can do Avatar asked Feb 07 '11 10:02

There is nothing we can do


3 Answers

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.

like image 60
Potatoswatter Avatar answered Oct 08 '22 01:10

Potatoswatter


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.

like image 31
GManNickG Avatar answered Oct 07 '22 23:10

GManNickG


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.

like image 2
Philipp Avatar answered Oct 07 '22 23:10

Philipp