Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Oct 24, 2001

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.
Ciprian Miclaus
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date