Listing 2
#include <memory>
#include <iostream>
using std::tr1::shared_ptr;
using std::cout;
struct node
{ // node for linked list
public:
node(int value) : data(value) {}
~node()
{ // destroy a node
cout << "destroying node holding " << data << '\n';
}
int get() const { return data; }
private:
friend struct list;
shared_ptr<node> next;
int data;
};
struct list
{ // simple linked list
public:
void insert(int value)
{ // add a value to the list
shared_ptr<node> elt(new node(value));
elt->next = items;
items = elt;
}
void show() const
{ // show all stored values
shared_ptr<node> elt = items;
while (elt)
{ // show a stored value
cout << elt->data << ' ';
elt = elt->next;
}
cout << '\n';
}
private:
shared_ptr<node> items;
};
void make_a_list()
{ // make a list and destroy it
list values;
values.insert(1);
values.insert(2);
values.insert(3);
values.show();
}
int main()
{ // demonstrate semi-automatic memory management
make_a_list();
return 0;
}