Why std::vector<>::pop_back() does not return the popped value?

I was curious why std::vector<>::pop_back() does not return the popped value. Instead, there is a pair of methods: void pop_back() and const_reference back() const.

The answer was obvious when I tried to implement a vector-like class myself. Here is the code for an implementation of a would-be T std::vector<>::pop_back():

	   T pop_back()
	   {
	      FSize -= 1;
	      // call copy ctor
	      T Copy( FArray[ FSize ] );
	      // call dtor
	      FArray[ FSize ].~T();
	      // return the copy - this can raise an exception,
	      // but the value has been already popped from the stack
	      return Copy;
	   }

The implementation of the canonical pop_back() is straightforward and does not perform any redundant fuss with copying:

	void pop_back()
	{
		FSize -= 1;
		// this is exception safe since the dtor never throws
		FArray[ FSize ].~T();
	}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.