C++ emplace vs push: Container Insertion and In-Place Construction

C++ emplace vs push: Container Insertion and In-Place Construction

이 글의 핵심

emplace vs push: when in-place construction wins, explicit ctor edge cases, and practical guidelines.

Most examples use std::vector; see the std::vector guide and the broader arrays and lists tradeoffs.

Introduction: “Is emplace_back always faster than push_back?”

emplace performs in-place construction and can skip temporaries for non-trivial types.

vec.push_back(std::string("Hello")); // temporary + move (conceptually)
vec.emplace_back("Hello");           // construct directly in storage

This article covers:

  • emplace vs push
  • Benchmarks (patterns)
  • Scenarios and caveats

Comparison table

Aspectpush_backemplace_back
ArgumentExisting objectctor args forwarded
TemporariesOften yesoften fewer
explicit ctorscannot implicit-convertcan construct

Performance

  • int loops: usually identical with optimizations
  • expensive types: emplace can reduce extra work—reserve still matters for reallocations

Guidelines

SituationPrefer
Already-built objectpush_back/push
Forward ctor argsemplace_back
Readability matters equallypick the clearer one

Caveats

  • explicit types: emplace can surprise—keep intent obvious
  • initializer_list ambiguity with vector<vector>—prefer clarity

  • Move semantics
  • Performance optimization

Keywords

emplace_back, push_back, in-place construction, C++ vector