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.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several