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


advertisement
 

Restrict Object Allocation to Specific Memory Types : Page 2

While C++'s three memory storage types provide an unparalleled degree of flexibility with respect to memory management, this diversity can sometimes make things more difficult—like when you need to allocate objects of a certain class exclusively on the free-store. Find out how to enforce memory allocation policies by controlling the access type of a class's member functions.


advertisement

Disabling Static and Automatic Objects
Smart pointer classes such as auto_ptrmust own objects that were allocated on the free-store. Alas, the compiler doesn't detect violations of this restriction:


#include <fstream>
#include <utility>

int main ()
{
 std::ofstream myfile;
std::auto_ptr<std::ofstream> file_ptr(&myfile);//disastrous!
}

auto_ptr's destructor calls delete to destroy myfile, although the latter was allocated on the stack. The result is undefined behavior. You can enforce this compile-time constraintby declaring the destructor as a private member:




class HeapOnly
{
private:
 ~HeapOnly();//auto and static objects are disabled
public:
 //..
};

How does this work? The compiler implicitly invokes the destructors of automatic and static objects when they go out of scope or when the program terminates, respectively. If the destructor isn't public, you get a compilation error, which is exactly what you want:


HeapOnly h1;//compilation error:
          //"Destructor for 'HeapOnly' is not accessible"
int main
{
 HeapOnly h2; // ditto
 static HeapOnly h3; //ditto
}

You can create such objects on the free-store. This raises yet another question: how do you destroy them? The solution is to delegate the destruction to another public member function:


class HeapOnly
{
private:
 ~HeapOnly();
public:
 void destroy() {delete this;} //invoke the destructor
};

HeapOnly * p = new HeapOnly;
//..use p
p->destroy()

Admittedly, this technique isn't perfect because you still can't bind auto_ptr to such an object. This time the problem is that auto_ptr's destructor can't delete p. However, it shouldn't be difficult to write an elementary smart pointer class whose destructor contains:


p->destroy;



Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap