Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To answer the question: you should not implement the pop function in C++, since it is already implemented by the STL. The <a href="http://en.cppreference.com/w/cpp/container/stack" rel="nofollow noreferrer"><code>std::stack</code></a> container adapter provides the method <code>top</code> to get a reference to the top element on the stack, and the method <code>pop</code> to remove the top element. Note that the <code>pop</code> method alone cannot be used to perform both actions, as you asked about.</p> <p>Why should it be done that way?</p> <ol> <li><strong>Exception safety:</strong> Herb Sutter gives a good explanation of the issue in <a href="http://www.gotw.ca/gotw/082.htm" rel="nofollow noreferrer">GotW #82</a>.</li> <li><strong>Single-responsibility principle:</strong> also mentioned in GotW #82. <code>top</code> takes care of one responsibility and <code>pop</code> takes care of the other.</li> <li><strong>Don't pay for what you don't need:</strong> For some code, it may suffice to examine the top element and then pop it, without ever making a (potentially expensive) copy of the element. (This is mentioned in the <a href="http://www.sgi.com/tech/stl/stack.html#3" rel="nofollow noreferrer">SGI STL</a> documentation.)</li> </ol> <p>Any code that wishes to obtain a copy of the element can do this at no additional expense:</p> <pre><code>Foo f(s.top()); s.pop(); </code></pre> <p>Also, <a href="http://www.eggheadcafe.com/software/aspnet/35709312/standard-library-pop.aspx" rel="nofollow noreferrer">this discussion</a> may be interesting.</p> <p>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 <a href="http://en.wikipedia.org/wiki/Return_value_optimization" rel="nofollow noreferrer">RVO</a>, 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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload