Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does push_back() always increase a vector's size?

I have a piece of code which creates a std::vector<T> with a known size:

std::vector<T> vectorOfTs(n);

Does calling push_back increase the size to n+1?

vectorOfTs.push_back(T());
like image 864
tunnuz Avatar asked Nov 27 '22 04:11

tunnuz


2 Answers

Yes; note that vector<T>.capacity() is different from vector<T>.size(). The latter denotes the number of elements currently in the vector while the former represents the number of items that fit in the space currently allocated for the vector's internal buffer.

like image 152
mmx Avatar answered Dec 18 '22 06:12

mmx


Almost. If there are no exceptions, then size() will increment.

push_back(T()) could also throw an exception at various stages: see here, or summarily:

  • T() construction, in which case no call to push_back takes place, and size() is unaffected

  • if the vector needs to increase the capacity, that may throw, in which case size() is unaffected

  • the vector element will be copy or move constructed using std::allocator_traits<A>::construct(m, p, v);, if A is std::allocator<T>, then this will call placement-new, as by ::new((void*)p) T(v): if any of this throws the vector's size() is unaffected, ****unless***

    • the move constructor isn't noexcept and does throw: in which case the effects are unspecified
  • the vector update's then complete - size() will have incremented and the value will be in the vector (even if T::~T())

like image 37
Tony Delroy Avatar answered Dec 18 '22 06:12

Tony Delroy