Quick background
I\'m a Java developer who\'s been playing around with C++ in my free/bored time.
Preface
In C++, you often see
To answer the question: you should not implement the pop function in C++, since it is already implemented by the STL. The std::stack container adapter provides the method top
to get a reference to the top element on the stack, and the method pop
to remove the top element. Note that the pop
method alone cannot be used to perform both actions, as you asked about.
Why should it be done that way?
top
takes care of one responsibility and pop
takes care of the other.Any code that wishes to obtain a copy of the element can do this at no additional expense:
Foo f(s.top());
s.pop();
Also, this discussion may be interesting.
If you were going to implement pop to return the value, it doesn't matter much whether you return by value or write it into an out parameter. Most compilers implement RVO, which will optimize the return-by-value method to be just as efficient as the copy-into-out-parameter method. Just keep in mind that either of these will likely be less efficient than examining the object using top() or front(), since in that case there is absolutely no copying done.