pop_back() return value?

Efficiency has little (or nothing, really) to do with it.

This design is the outcome of an important paper by Tom Cargill, published in the 90s, that raised quite a few eyebrows back then. IIRC, in it Cargill showed that it is impossible to design an exception safe stack pop function.


I think there is something related to the fact that copying an instance of the last object could throw an exception. When doing so, you're losing your object, since pop_back() did remove it from your container. Better with a few lines of code:

std::vector<AnyClass> holds = {...} ;
try {
  const AnyClass result = holds.pop_back(); // The copy Ctor throw here!
} catch (...)
{ 
 // Last value lost here. 
}

It's because of the Command-query separation principle.


Efficiency is one thing. Another reason for pop_back() not returning an element is exception safety.
If the pop() function returned the value, and an exception is thrown by the copy constructor, you may not be able to guarantee that the container is in the same state as it was before calling pop().

You can find more infos in Herb Sutters books about exceptions. I think this topic is covered here. But I am not sure.


The reason is not so much efficiency as exception safety. The container class can be used to store any kind of objects. It would be impossible to implement pop_back() in an exception safe manner if the function would return the object after deleting it from the container, because returning the value of the object involves copy construction.

This is the actual implementation of vector::pop_back() in GNU C++ standard library:

  void
  pop_back()
  {
    --this->_M_impl._M_finish;
    this->_M_impl.destroy(this->_M_impl._M_finish);
  }

This is what it would look like should it return the last element in the end:

  value_type
  pop_back()
  {
    value_type save = back();
    --this->_M_impl._M_finish;
    this->_M_impl.destroy(this->_M_impl._M_finish);
    return save;
  }

This involves two copy constructions, at the save = back() statement and when returning a copy of the object. There are no guarantees that the return expression won't throw an exception after the element has been destroyed from the container.