Store results of std::stack .pop() method into a variable

The standard library containers separate top() and pop(): top() returns a reference to the top element, and pop() removes the top element. (And similarly for back()/pop_back() etc.).

There’s a good reason for this separation, and not have pop remove the top element and return it: One guiding principle of C++ is that you don’t pay for what you don’t need. A single function would have no choice but to return the element by value, which may be undesired. Separating concerns gives the user the most flexibility in how to use the data structure. (See note #3 in the original STL documentation.)

(As a curiousum, you may notice that for a concurrent container, a pop-like function is actually forced to remove and return the top value atomically, since in a concurrent context, there is no such notion as “being on top” (or “being empty” for that matter). This is one of the obvious examples of how concurrent data structures take a significant performance hit in order to provide their guarantees.)

Leave a Comment