------------------------------------------------------------------------------
MC logo
Classy Auto 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]
apinclass.cpp
#include <iostream>
#include <memory>
#include <string>

using namespace std;

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

class Holder {
public:
        Holder(string s) { m_a0.reset(new Announcer(s)); }
        void set1(string s) { m_a1.reset(new Announcer(s)); }
        void set2(string s) { m_a2 = auto_ptr<Announcer>(new Announcer(s)); }
        void pr() { 
                cout << m_a0->get() << " " << m_a1->get() 
                     << " " << m_a2->get() << endl; 
        }
private:
        auto_ptr<Announcer> m_a0, m_a1, m_a2;
};

main()
{
        Holder h("Frank");
        h.set1("is");
        h.set2("gone.");

        h.pr();
}

The auto_ptr can also be used for object data. When the object is destroyed, whatever the auto_ptr fields point to is also destroyed. This may relieve you from having to write a destructor for the class.