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());
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.
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***
noexcept
and does throw: in which case the effects are unspecifiedthe vector update's then complete - size()
will have incremented and the value will be in the vector
(even if T::~T()
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With