C++ Reference ยท Containers
std::vector::push_back and emplace_back
Reference for vector::push_back and emplace_back: copying versus moving versus constructing in place, return values, reallocation, and the exception guarantee.
push_back appends a copy or a moved version of an existing object to the end of a vector. emplace_back constructs the new element in place from constructor arguments, so no temporary object is needed. Both run in amortized constant time: most calls just write into spare capacity, and occasionally a call reallocates the buffer and moves every element.
Choose push_back when you already have the object (or a braced list for it), and emplace_back when you have the arguments needed to build it. For cheap types such as int there is no measurable difference.
v.push_back(x); // copy x (or move it: v.push_back(std::move(x))) v.emplace_back(a, b); // construct T(a, b) directly inside the vector
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
void push_back(const T& value); // copies value void push_back(T&& value); // moves value template <class... Args> reference emplace_back(Args&&... args); // returns T& since C++17 (void before)
| Name | Description |
|---|---|
value |
The object to copy or move into the new last element. |
args |
Arguments forwarded to the constructor of T. |
Returns: push_back returns nothing. emplace_back returns a reference to the new element (C++17).
Errors / undefined behavior:
- If an exception is thrown while constructing the new element,
push_backandemplace_backleave the vector unchanged (strong guarantee), as long asT's move constructor isnoexceptorTis copyable. If a throwing move constructor is the only option, the guarantee is weaker. - Can throw
std::bad_allocorstd::length_error. - Adding an element may reallocate, which invalidates all iterators, pointers and references.
v.push_back(v[0])is still valid: the implementation handles self-references correctly.
Usage notes
- No magic speed-up:
emplace_backonly saves the temporary.v.emplace_back(Tracer("c"))builds a temporary anyway and loses the benefit. - Explicit constructors:
emplace_backcan call explicit constructors, andpush_back("text")for avector<std::string>works through an implicit conversion.emplace_backtherefore hides mistakes:std::vector<std::unique_ptr<int>> v; v.emplace_back(new int(1));compiles, but leaks if the allocation for the vector's growth throws. Preferv.push_back(std::make_unique<int>(1)). - Move-only types need
push_back(std::move(x))oremplace_back(...). - Mark move constructors
noexcept: otherwise a reallocation copies rather than moves the elements, becausestd::move_if_noexceptis used. - Growth: capacity grows geometrically, so n appends cost O(n) in total. The factor is implementation-defined; the standard only guarantees the amortized bound. See reserve and capacity.
- Appending a range: use
v.append_range(r)(C++23),v.insert(v.end(), first, last)orstd::back_inserterwith an algorithm instead of looping. - Don't call it while iterating with iterators or a range-based for loop over the same vector.
std::vector<bool>supports both, butemplace_backthere constructs abool; see vector<bool>.