Tutorials All - Webdesign, Graphic Design

Visit our new Webdesign Templates,css,html5 etc

Download New Android Applications

Visit our new Collections of Android Application

1.10.12

Using auto_ptr to Handle Memory

The auto_ptr template class is designed to help manage memory in a semi-automatic way and prevent memory leaks when unexpected events such as exceptions would otherwise have caused the normal cleanup code to be skipped.


For instance, it is common to write code such as
void myFunction()
{
    myClass = new myClass();
    // body of function
    delete myClass;
}
and this may work. But what if somewhere in the function body an exception gets thrown? Suddenly, the delete code never gets called! What's more, you may never have intended to throw an exception into the function but one of the functions you call may do so, or you may later need to modify your code to do so. In both cases, this is a memory leak waiting to happen.

On the other hand, by letting the auto_ptr class manage your memory for you, as soon as an exception gets thrown and the auto_ptr you declared has gone out of scope, the memory allocated will automatically be freed. First, let's look at how to use auto_ptr, and then I'll explain the exact mechanics of how this works.
Read More : Click Here