devxlogo

Enforcing a Class Object to Be Allocated on the Free Store

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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist