Reputation: 24705
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
}
Upvotes: 15
Views: 7498
Reputation: 163
Because you can then enforce that an object is always allocated dynamically i.e. with a new operator. To make that work you would need to implement a dispose() method that calls "delete this" before it returns. This makes it possible to create finalizing methods that are called before an object or a part of an object is destroyed and so can safely delete or disconnect instance members before virtual destructors chain is getting called.
Upvotes: 0
Reputation: 31455
You can create one on the stack only in the scope that has access to the destructor. Therefore you could do so in a friend function or static member function of the class (or even a regular class member).
The end of the function for a local variable is responsible for deleting therefore must be able to call the destructor, albeit implicitly.
You can create one with new from anywhere if you have access to the appropriate constructor.
If you use it in a smart-pointer you must ensure where it gets deleted has access. This may vary for different smart-pointers, and for some you can provide a custom destructor which could be a static member of the class.
Upvotes: 2
Reputation: 504333
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.
Upvotes: 10
Reputation: 49850
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.
Upvotes: 2
Reputation: 137960
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.
Upvotes: 19