MC logo
Automatically Deleting Pointer
[^] CSc 220 Home
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Automatically Deleting Pointer] [Classy Auto Pointer]
#include <iostream>
#include <memory>
#include <string>

using namespace std;

class Announcer {
        Announcer(string s = "") { 
                m_str = s; 
                cout << "Create " << s << endl;
        void set(string s) { m_str = s; }
        ~Announcer() { cout << "Delete " << m_str << endl; }
        string m_str;

void f0()
        Announcer *foo = new Announcer("Created by 0");
        foo->set("Bye 0");
        delete foo;

void f1()
        Announcer *foo = new Announcer("Created by 1");
        foo->set("Bye 1");

void f2()
        auto_ptr<Announcer> foo(new Announcer("Created by 2"));
        foo->set("Bye 2");

        cout << "f0 is correct, using delete to clean up." << endl;
        cout << "\nf1 is incorrect, since it creates garbage." << endl;
        cout << "\nf2 is correct, letting auto_ptr clean up." << endl;

The auto_ptr<T> is a very nice library template class which automates dynamic memory cleanup in one common, simple case. auto_ptr<T> behaves just like a pointer to T, except that when the pointer itself is destroyed (in this case by going out of scope), what it points to is also destroyed.

Be very careful that you don't have more than one auto_ptr object pointing to the same place. Then you will delete it twice, which is very bad.