Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pop_back() return value?

Tags:

c++

vector

Why doesn't pop_back() have a return value? I have Googled regarding this and found out that it makes it more efficient. Is this the only reason for making it so in the standard?

like image 869
Parvinder Singh Avatar asked Sep 26 '12 11:09

Parvinder Singh


People also ask

Does Pop_back return value?

+1 this is the correct answer. It tells us the underlying principle which led to this design of pop_back with no return value.

What does Pop_back function do in C++?

pop_back() is used to remove/pop the element from the back or the last of the list container. When we use pop_back then it remove/pops the last element and the element before the last element becomes the last element and the size of the list container is reduced by 1.

What does vector Pop_back do?

vector::pop_back()() pop_back() function is used to pop or remove elements from a vector from the back. The value is removed from the vector from the end, and the container size is decreased by 1.

Does Pop_back reduce size?

No. pop_back() will not shrink the capacity of vector.


Video Answer


2 Answers

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.

like image 78
sbi Avatar answered Sep 30 '22 17:09

sbi


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.  } 
like image 32
yves Baumes Avatar answered Sep 30 '22 19:09

yves Baumes