Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::vector::emplace_back — construct an element at the end

Construct one element at the end of a vector from its arguments. Learn what the function returns and when appending invalidates existing references.

Version: ISO C++23; implementation support may vary

Syntax

#include <vector>

// Member declaration inside std::vector<T, Allocator> (C++23):
template<class... Args>
constexpr reference emplace_back(Args&&... args);

// Call on a vector v:
v.emplace_back(args...);

std::vector::emplace_back, declared in <vector>, appends one element and increases size() by one on success. The Args&&... parameters are forwarding references: std::forward preserves the lvalue/rvalue distinction, but forwards a prvalue as an xvalue. In the primary template, the element of type T is constructed directly in the vector's storage by calling std::allocator_traits<Allocator>::construct with the forwarded arguments. T must be EmplaceConstructible from those arguments and MoveInsertable into that vector, even if there is already enough capacity. The std::vector<bool> specialization is not required to use allocator_traits::construct to construct its values.

emplace_back can use an explicit constructor without the caller creating a temporary T. If you already have a T, push_back clearly expresses copying it (const T&) or passing it for a move (T&&). Emplacement does not guarantee that no copies or moves occur. The function returned void in C++11 and C++14; since C++17 it returns reference to the new element (T& in the primary template, a proxy object in std::vector<bool>). It is constexpr since C++20, subject to the rules for constant evaluation.

Appending is amortized constant time; a call that reallocates is linear in the number of elements. If the new size exceeds the old capacity(), reallocation invalidates all existing pointers, references and iterators to elements, as well as the old end(). Without reallocation, only the old end() is invalidated. A successful reserve(n) ensures capacity of at least n but does not change size() or create elements.

If insertion throws, the vector is normally unchanged. However, if the exception comes from the move constructor of a T that is not CopyInsertable into that vector, the effects are unspecified. Do not use invalidated references or pointers to access elements.

Examples

#include <iostream>
#include <string>
#include <utility>
#include <vector>

struct Result {
    std::string name;
    int score;

    explicit Result(std::string n, int s) : name(std::move(n)), score(s) {}
};

int main() {
    std::vector<Result> results;
    results.reserve(2);
    std::cout << "size after reserve: " << results.size() << '\n';

    auto& first = results.emplace_back("Ada", 40);
    results.emplace_back("Lin", 35);
    first.score += 2;

    std::cout << "size after insertion: " << results.size() << '\n';
    for (const auto& result : results) {
        std::cout << result.name << ": " << result.score << '\n';
    }
}

Result

size after reserve: 0
size after insertion: 2
Ada: 42
Lin: 35

`reserve(2)` creates no elements but ensures that neither insertion reallocates. So `first` still refers to the first result, and updating it changes Ada's score from 40 to 42.

Related lessons

  • C++ · Lesson 18 · Advanced · Version: 3
  • C++ · Lesson 32 · Advanced · Version: 3
  • C++ · Lesson 36 · Advanced · Version: 3

Sources