Yes, destructor can be private and it is not true that class cannot be instantiated.
Private Destructor in C++ This code has private destructor, but it will not generate any error because no object is created.
There's nothing inherently wrong with making the destructor protected or private, but it restricts who can delete the pointer.
Advantages of Destructor in C++It gives a final chance to clean up the resources that are not in use to release the memory occupied by unused objects like deleting dynamic objects, closing of the system handles, used files.
Basically, any time you want some other class to be responsible for the life cycle of your class' objects, or you have reason to prevent the destruction of an object, you can make the destructor private.
For instance, if you're doing some sort of reference counting thing, you can have the object (or manager that has been "friend"ed) responsible for counting the number of references to itself and delete it when the number hits zero. A private dtor would prevent anybody else from deleting it when there were still references to it.
For another instance, what if you have an object that has a manager (or itself) that may destroy it or may decline to destroy it depending on other conditions in the program, such as a database connection being open or a file being written. You could have a "request_delete" method in the class or the manager that will check that condition and it will either delete or decline, and return a status telling you what it did. That's far more flexible that just calling "delete".
Such an object can never be created on the stack. Always on the heap. And deletion has to be done via a friend or a member. A product may use a single Object hierarchy and a custom memory-manager -- such scenarios may use a private dtor.
#include <iostream>
class a {
~a() {}
friend void delete_a(a* p);
};
void delete_a(a* p) {
delete p;
}
int main()
{
a *p = new a;
delete_a(p);
return 0;
}
When you do not want users to access the destructor, i.e., you want the object to only be destroyed through other means.
http://blogs.msdn.com/larryosterman/archive/2005/07/01/434684.aspx gives an example, where the object is reference counted and should only be destroyed by the object itself when count goes to zero.
COM uses this strategy for deleting the instance. COM makes the destructor private and provides an interface for deleting the instance.
Here is an example of what a Release method would look like.
int MyRefCountedObject::Release()
{
_refCount--;
if ( 0 == _refCount )
{
delete this;
return 0;
}
return _refCount;
}
ATL COM objects are a prime example of this pattern.
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