/* * Another variation on the linked stack, this time using the unique_ptr * library class to manage memory allocation. We still don't need a * destructor. */ #ifndef _lnkstack4_h_ #define _lnkstack4_h_ #include #include using std::unique_ptr; template 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_unique(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 = std::move(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 == nullptr; } // 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, unique_ptr &n = nullptr) { m_data = d; m_next = std::move(n); // The move operation leaves n NULL, moving the // pointer, and reponsibility for it, to m_next. } const T& data() { return m_data; } unique_ptr &next() { return m_next; } private: T m_data; unique_ptr m_next; }; unique_ptr m_head; int m_size; }; #endif