skip to content

In C++, how does std::vector::emplace_back differ from push_back, and when is emplace_back no faster or even riskier?

level: middleimportance: should knowfreq 62%

answer

  1. an object vs constructor arguments
  2. the temporary that is skipped
  3. direct-initialization reaches explicit
  4. new T inside emplace_back

basics

~20 s

push_back takes an element-type object, building a temporary if needed and moving it in; emplace_back forwards arguments to a constructor and builds the element in place. With an existing object they do the same work, and emplace_back can call explicit constructors.

solid answer

~40 s

`push_back` has two overloads, `const T&` and `T&&`, so its argument must already be a `T` or convert implicitly to one; passing constructor arguments creates a temporary that is then moved in. `emplace_back(args...)` forwards the arguments to a `T` constructor and constructs the element directly in the vector's storage, saving that one move. If you already hold an object, `push_back(p)` and `emplace_back(p)` perform the same copy. Because `emplace_back` uses direct-initialization, it also reaches `explicit` constructors: `frames.emplace_back(1000000)` on a `std::vector<std::vector<int>>` silently creates a million-element vector where `push_back` would not compile, and `emplace_back(new Emitter)` into a vector of `std::unique_ptr` leaks if the reallocation throws. Since C++17 `emplace_back` returns a reference to the new element, and since C++20 it accepts aggregate arguments in parentheses.

code

cpp · 24 lines
cpp
#include <cstdio>
#include <vector>

struct Particle {
    float x, y;
    Particle(float px, float py) : x(px), y(py) { std::puts("  construct"); }
    Particle(const Particle& o) : x(o.x), y(o.y) { std::puts("  copy"); }
    Particle(Particle&& o) noexcept : x(o.x), y(o.y) { std::puts("  move"); }
};

int main() {
    std::vector<Particle> v;
    v.reserve(4);                       // keep reallocation out of the count
    std::puts("push_back(Particle(1, 2)):");
    v.push_back(Particle(1, 2));
    std::puts("push_back({3, 4}):");
    v.push_back({3, 4});
    std::puts("emplace_back(5, 6):");
    Particle& p = v.emplace_back(5, 6);  // returns a reference since C++17
    std::printf("  back is (%g, %g)\n", p.x, p.y);
    Particle existing(7, 8);
    std::puts("emplace_back(existing):");
    v.emplace_back(existing);
}

go deeper

for a junior

Know that push_back takes an object and emplace_back takes constructor arguments, and that with an existing object both do the same copy or move.

for a middle

Count the constructor calls for each form, explain the temporary that emplace_back avoids, and name the C++17 return value change.

for a senior

Spot the review hazards: explicit constructors reachable through emplace_back, raw new passed into a vector of unique_ptr, and braced lists that only push_back accepts.

for a principal

Set a team convention that prefers clarity: push_back for objects, emplace_back for in-place construction, and a lint or review rule against raw new inside emplace calls.

## Two ways to append `std::vector<T>` has two families of append functions: - **`push_back`** has two overloads, `push_back(const T&)` and `push_back(T&&)`. Its argument must already be a `T`, or something that converts **implicitly** to `T`. When you pass anything else, a temporary `T` is created first and then moved (or copied) into the vector. - **`emplace_back(Args&&... args)`** is a variadic template. It forwards its arguments to a constructor of `T` and constructs the new element directly in the vector's storage, with no temporary. Since C++17 it returns a `reference` to the new element; in C++11 and C++14 it returned `void`. How the arguments are forwarded is the subject of perfect forwarding; what matters here is which constructor runs and how many times. ## Counting constructor calls With a particle type whose constructor takes two floats, and capacity reserved so that reallocation does not distort the count, a libc++ run prints: | Call | Constructor calls | |---|---| | `v.push_back(Particle(1, 2))` | construct, then move | | `v.push_back({3, 4})` | construct, then move | | `v.emplace_back(5, 6)` | construct | | `v.emplace_back(existing)` | copy | So the saving is one move-constructor call, and only when you pass constructor arguments rather than an object. For types whose move is cheap, such as a few floats or a type holding a pointer, the difference is negligible. When you already hold a `Particle`, `push_back(p)` and `emplace_back(p)` perform the same copy, and `push_back(std::move(p))` and `emplace_back(std::move(p))` the same move. ## When the saved move matters - **Expensive moves**: types that keep their data inline, such as a struct holding a large `std::array` of floats, copy those bytes even when moved, so skipping the temporary saves real work. - **Cheap moves**: `std::string`, `std::vector` or `std::unique_ptr` elements move by copying a few words, and the difference rarely shows up in a profile. - **No difference**: when the argument is already an object of the element type, both functions perform the same copy or move. - **Still movable**: for `std::vector`, both functions require an element type that can be moved or copied, because a reallocation has to transfer the existing elements. `emplace_back` does not make a `std::mutex` member acceptable. ## Where emplace_back is riskier Because `emplace_back` performs **direct-initialization**, it can call constructors that `push_back` would refuse: 1. **Explicit constructors.** `std::vector<std::vector<int>> frames; frames.push_back(1000000);` does not compile, because the `vector(size_type)` constructor is `explicit`; clang reports "no matching member function for call to 'push_back'". `frames.emplace_back(1000000);` compiles and appends a vector of one million zeros, so a typo becomes a large allocation. 2. **Raw owning pointers.** With `std::vector<std::unique_ptr<Emitter>> emitters`, `emitters.push_back(new Emitter)` is rejected because the `unique_ptr` constructor from a raw pointer is `explicit`, while `emitters.emplace_back(new Emitter)` compiles. If the vector has to reallocate and that allocation throws, the raw pointer was never owned by a `unique_ptr`, and the `Emitter` leaks. Write `emitters.push_back(std::make_unique<Emitter>())` instead. 3. **Braced lists.** `v.emplace_back({1.f, 2.f})` does not compile: a braced-init-list has no type, so the template cannot deduce `Args`. `v.push_back({1.f, 2.f})` works because its parameter type is already `T`. ## Aggregates and the standard revision For an aggregate with no constructors, such as `struct Particle { float x, y; };`, the call `emplace_back(1.f, 2.f)` does not compile under C++17. The library constructs the element with parentheses, as in `T(args...)`, and C++17 cannot aggregate-initialize from a parenthesized list; clang reports "no matching constructor for initialization of 'Particle'". C++20 added parenthesized aggregate initialization (feature-test macro `__cpp_aggregate_paren_init`), so the same call compiles under C++20 and later. Under C++17, `push_back({1.f, 2.f})` is the way to append an aggregate. ## A rule of thumb that holds up in review - Use `push_back` when you already have an object of the element type, or when you want explicit constructors kept out of reach. - Use `emplace_back` when you pass constructor arguments and the element is expensive to move, and read the call as "calls a constructor of `T` with these arguments". - Use the C++17 return value instead of a separate `back()` call: `auto& p = particles.emplace_back(x, y);`. - Remember that both functions follow the same growth rules. Either one may reallocate, and reserving capacity first is what removes that cost.

  • Is v.emplace_back(std::move(p)) any faster than v.push_back(std::move(p)) when p is already a Particle?
    No. Both end up calling the move constructor of `Particle` once to create the element in the vector's storage; `emplace_back` simply forwards the rvalue to that constructor, and `push_back(T&&)` does the same. The only saving `emplace_back` offers is skipping a temporary when you pass constructor arguments instead of an object.
  • Why does emplace_back(new Emitter) risk a leak in a vector of std::unique_ptr<Emitter>, while push_back(std::make_unique<Emitter>()) does not?
    With `emplace_back(new Emitter)`, the raw pointer travels into the function unowned, and the `unique_ptr` is only constructed after any reallocation succeeds; if that allocation throws, nothing deletes the `Emitter`. With `make_unique`, ownership exists before the call, so if `push_back` throws, the temporary `unique_ptr` is destroyed during unwinding and frees the object.

  • emplace_back is always faster than push_back, so push_back is obsolete
  • push_back(Particle(1, 2)) copies the temporary into the vector
  • emplace_back and push_back accept exactly the same set of arguments
  • emplace_back(new T) is a safe way to fill a vector of unique_ptr
  • emplace_back never reallocates because it constructs in place

Assumes C++17 or later: emplace_back returns a reference since C++17, and aggregate elements can be emplaced from parenthesized arguments only since C++20.