Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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.




Application Security Testing: An Integral Part of DevOps

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
 ~HeapOnly();//auto and static objects are disabled

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
 void destroy() {delete this;} //invoke the destructor

HeapOnly * p = new HeapOnly;
//..use p

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:


Comment and Contribute






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



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