I'm currently working on implementing overloaded operators for simplifying pop() and push() operations. Check out the //how can avoid this? comments. I've had some troubles understanding how to return a certain value without causing memory leaks due to unassigned free space: so far the only dirty and inelegant idea I've had was to create a temporary empty value of T type, so in case the top pointer contained nullptr I could return this empty value.But how can I avoid this? Or is this actually necessary in a template type for a function with return statements?#include <iostream>#include <memory>#include <string>#include <vector>template <typename V> using ptr = std::shared_ptr<V>;template <typename T>class Stack{private:    class Node    {    private:        T data;        ptr<Node> next;    public:        Node(T _data):data{_data}, next{} {}        T getData(){            return data;        }        ptr<Node>& getNext(){            return this->next;        }    };    ptr<Node> top;public:    Stack() : top{} {}    Stack(const std::shared_ptr<std::vector<T>>& vec) : top{} {        for (auto vElement : *vec){            push(vElement);        }    }    void push(T _data){        auto _tmp = std::make_shared<Node>(_data);        if(top!= nullptr){            _tmp->getNext() = top;        }        top = _tmp;    }    T pop(){        T forSafety{}; //how can I avoid this?        if(isEmpty()) return forSafety;        else {            auto _tmp = top;            top = top->getNext();            return _tmp->getData();        }    }    T peek(){        T forSafety{}; //how can I avoid this?        if(!isEmpty()){            return top->getData();        } else return forSafety;    }    bool isEmpty(){        if(top==nullptr) return true;        else return false;    }    void display(){        auto _tmp = top;        while(_tmp!=nullptr){            std::cout << _tmp->getData() << std::endl;            _tmp = _tmp->getNext();        }    }};int main(int argc, char** argv){    std::shared_ptr<std::vector<std::string>> names{new std::vector<std::string>{Julia,Bob,Angela,fSociety}};    auto s = std::make_shared<Stack<std::string>>(names);    s->display();    std::cout << s->peek() << std::endl;    while(!s->isEmpty()){        std::cout << Popping ->  << s->pop() << std::endl;    }    s->display();    s->peek();    return 0;}
Implementation of the Stack data structure using a linked list in C++
c++;c++11;linked list;stack