Heap Only Objects
Let's discuss ways of restricting objects so that they can only be created on the heap. Meyers explains that sometimes a developer wants to create objects that can destroy themselves by calling delete this. If an attempt was made to create such an object on the stack the effects could be catastrophic, so it makes sense to enforce heap creation.
Scott Meyers forces heap-only creation by making the object's destructor private (or protected if you want to be able to inherit from the object) and implementing a disposal method. For example:
Even Constructor of a class can be made private not to create object on stack. But constructor has many variants, (Constructor with no argument, constructor with arguments). So we made destructor as private. Because destructor will be only one per class.
Even Constructor of a class can be made private not to create object on stack. But constructor has many variants, (Constructor with no argument, constructor with arguments). So we made destructor as private. Because destructor will be only one per class.
class HeapOnly {
private:
~HeapOnly() {}
public:
// Disposal Method
void Destroy() { delete this; }
};
If an attempt is made to create this object on the stack:
int main() {
HeapOnly heapOnly;
}
the compiler will issue an error.
However, if the object is created on the heap:
int main() {
HeapOnly* pHeapOnly = new HeapOnly;
pHeapOnly->Destroy();
}
the compiler is perfectly happy.
In terms of forcing objects to be created on the heap, Meyers's example does exactly what is needed. However, it does have one drawback. The developer using the heap-only object must explicitly call Destroy in order to prevent a memory leak.
Comments
Post a Comment