Enforcing a Class Object to Be Allocated on the Free Store

Sometimes you need to enforce objects of a certain type to be allocated only on the free store (heap) rather than on the stack.That’s if you need somewhere to call a delete on a pointer. If the pointer points to something on the stack and you try to delete it, it’ll crash miserably.

You could declare the destructor of the class private or protected, and have a desctructing method that replaces the destructor:

 class CHeap { public:  CHeap ();  DeleteThis ()  { delete this; } private:  ~CHeap ();};

Using this method, the class cannot be instantiated on the stack, and the compiler will throw an error, since it cannot call the private/protected destructor when the variable goes out of scope. The only alternative is to allocate it dynamically on the free store:

 CHeap* heap = new CHeap;

When you’re finished, you can prevent memory leaks by calling heap->DeleteThis (). Remember that after calling DeleteThis, you have a dangling pointer and if you try to access it you may end up with Access Violation or core dump.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: