November 2001
Beginner
1128 pages
29h 12m
English
The auto_ptr class is a template class for managing the use of dynamic memory allocation. Let's take a look at what might be needed and how it can be accomplished. Consider the following function:
void remodel(string & str)
{
string * ps = new string(str);
...
str = ps;
return;
}
You probably see its flaw. Each time the function is called, it allocates memory from the heap but never returns it, creating a memory leak. You also know the solution—just remember to free the allocated memory by adding the following statement just before the return statement:
delete ps;
However, a solution involving the phrase “just remember to” seldom is the best solution. Sometimes you won't remember. Or you will remember but accidentally remove ...