Linked Stack Using Shared Pointer
/* * Another variation on the linked stack, this time using the shared_ptr * library class to manage memory allocation. We no longer need a * destructor. */ #ifndef _lnkstack3_h_ #define _lnkstack3_h_ #include <utility> #include <memory> using std::shared_ptr; template <typename T> class Stack { public: Stack() { m_size = 0; } // Push the argument item. void push(const T &itm) { // Create a new node, holding it in a unique ptr. (The // make_unique method is from the 2014 standandard.) m_head = std::make_shared<node>(itm, m_head); ++m_size; } // Pop the argument item, and return true, or return false if the // the stack is empty. bool pop(T &itm) { if(!m_head) return false; itm = m_head->data(); m_head = m_head->next(); --m_size; return true; } // Convenience to pop and return the top object. Only works // for types where T() is a valid expression. T pop() { T ret; if(pop(ret)) return ret; return T(); } // Tell if empty. bool empty() { return m_head; } // Report the size int size() { return m_size; } private: // Nodes for the linked list. class node { public: // Constructor for a node. Saves the arguments. node(const T &d, shared_ptr<node> n = nullptr) { m_data = d; m_next = n; } const T& data() { return m_data; } shared_ptr<node> next() { return m_next; } private: T m_data; shared_ptr<node> m_next; }; shared_ptr<node> m_head; int m_size; }; #endif

Another linked stack. This uses the shared_ptr smart pointer, which provides garbage collection. Instead of declaring any pointers, we declare shared_ptr. We allocate objects with the make_shared utility instead of new.

The shared_ptr uses a technique called reference counting to keep track of how many pointers exist to each allocated node. This is updated whenever a pointer is created, copied or destroyed. When the count reaches zero, the object is deleted. This means that we don't need to worry about deleting nodes when done.

It also means that we do not need a destructor. When stack object itself is destroyed, the m_head pointer is destroyed. This i the only pointer to the first node, which is deleted. This causes the second node be be deleted, and the whole stack disappears, automatically.

One other small difference: the constructor didn't need to set the head pointer to null, since shared_ptr's initialize themselves to null.