beautypg.com

Example program, Chapter 19, Example – HP Integrity NonStop H-Series User Manual

Page 232: Program of auto_ptr

background image

Click on the banner to return to the user guide home page.

©Copyright 1996 Rogue Wave Software

Example Program

This program illustrates the use of

auto_ptr

to ensure that pointers held in a vector are deleted

when they are removed. Often, we might want to hold pointers to strings, since the strings
themselves may be quite large and we'll be copying them when we put them into the vector.
Particularly in contrast to a string, an auto_ptr is quite small: hardly bigger than a pointer. (Note
that the program runs as is because the vector includes memory.)

Obtaining the Sample Program.

#include
#include
#include

int main()
{
{
// First the wrong way
vector v;
v.insert(v.begin(), new string("Florence"));
v.insert(v.begin(), new string("Milan"));
v.insert(v.begin(), new string("Venice"));

// Now remove the first element

v.erase(v.begin());

// Whoops, memory leak
// string("Venice") was removed, but not deleted
// We were supposed to handle that ourselves
}
{
// Now the right way
vector > v;
v.insert(v.begin(),
auto_ptr(new string("Florence")));
v.insert(v.begin(), auto_ptr(new string("Milan")));

This manual is related to the following products: