Linked Stack Using Shared Pointer
/* * This version uses the shared_ptr to manage memory. This is much * easier to work with than the unique_ptr, though probably produces * a slower run-time program. */ #ifndef _lnkstack4_h_ #define _lnkstack4_h_ #include <memory> using std::shared_ptr; template <typename T> class Stack { public: // Initialize the stack empty. Stack() { } // Thou shalt not. Stack(const Stack<T>&) = delete; Stack & operator=(const Stack<T>&) = delete; // Push the argument item. void push(const T &itm) { m_head = shared_ptr<node>(new node(itm, m_head)); } // Pop the argument item, and return true, or return false if the // the stack is empty. bool pop(T &itm) { if(m_head == NULL) return false; itm = m_head->data(); m_head = m_head->next(); return true; } // Tell if empty. bool empty() { return m_head == NULL; } private: // Nodes for the linked list. class node { public: node(const T &d, shared_ptr<node> n = NULL) { 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; }; #endif

And one more linked stack. This uses the shared_ptr smart pointer, which is a bit more flexible and easier to use. The constructor is similar to the unique_ptr version, and likewise there is no need for a destructor. The pop method is rather simpler than the the unique_ptr version, since now we just need:

m_head = m_head->next();
The shared_ptr can do the necessary record-keeping with just the assignment statement. The node class is also simpler, no longer needing to pass the pointer by reference. shared_ptr is not so allergic to being copied.