This one has annoyed me for a while until I found the answer as pre STL stack classes used to have a pop()
function that was popping the element and returning it to the user. I was finding it conveniant because everytime I wanted to access the top element, I also wanted to pop out the element of the stack so why STL containers is forcing its users to perform this common operation with 2 operations?
In 'The C++ Programming Language' book, Bjarne Stroustrup has this to say about pop_back:
Note that
pop_back()
does not return a value. It just pops, and if we want to know what was on the top of the stack before pop, we must look. This happens not to be my favorite style of stack, but it's arguably more efficient and it's the standard.
I wish that he took the time to explain his position about why it is more efficient for pop_back()
to not return the element but I only understand why it was done like that by reading the book Exceptionnal C++ from Herb Sutter.
If you are using a STL container to store pointers, the performance argument disapear but if you store objects, all front()
is returning is a reference to the top element and if pop_front()
would return the top element, it would be by value and the copy constructor and the assignement operator would be involved. This is the performance argument that by having to call these 2 functions, it is adding overhead.
However, I suspect that this is not the main reason to have separated the 2 operations. Probably that the main reason is for exception safety garantee that the STL containers provide. Since, one requirement that STL impose on its users that contained objects destructors cannot throw exceptions, pop_front()
can provide a no throw garantee. It could not if it had to return the top element because if the copy constructor or the assignment operator was throwing an exception, the element would be lost forever. In contrast, when an exception is thrown while assigning front()
result, if you can cope with the exception, the element is not lost because it is still in the container.
I want you to find in this blog informations about C++ programming that I had a hard time to find in the first place on the web.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
<< < | Current | > >> | ||||
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |