I don't understand why do we can't do it in a single method ?
The two operations are needed to give a strong exception guarantee - that is, if an exception is thrown at any time, the container should not be changed.
Your proposal, auto v = something.pop()
, has to do three things in order:
- Remove an element from the container;
- Return that element from the function;
- Initialise
v
with the returned value.
If the final stage throws an exception, then the element will have been removed from the container and lost. Your attempt to fix that with a try...catch
construct won't help: the exception will be thrown after returning from the function, and so will not be caught by a handler in the function.
Doing it in two stages with an STL-style interface, the order is instead:
- Process a reference to the container element;
- Remove the element from the container.
Now if the processing throws an exception, the element remains in the container and is not lost.
These days, with move semantics added to the language, you could implement your version, with a requirement that elements do not throw when moved. That's a fairly reasonable requirement, already made by some operations on C++11 containers. But that hasn't happened, and I doubt that such a change would be made just for a minor convenience.
If we realy care about an exception that can be throw in the copy constructor and we realy want to continue AND to keep the data, can't we simply try catch around the 'pop' method ?
We could; but that's less convenient, and much more error-prone, than providing an exception-safe interface.