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
| Aspect | push_back | emplace_back |
|---|---|---|
| Argument | Existing object | ctor args forwarded |
| Temporaries | Often yes | often fewer |
| explicit ctors | cannot implicit-convert | can construct |
Performance
- int loops: usually identical with optimizations
- expensive types: emplace can reduce extra work—reserve still matters for reallocations
Guidelines
| Situation | Prefer |
|---|---|
| Already-built object | push_back/push |
| Forward ctor args | emplace_back |
| Readability matters equally | pick the clearer one |
Caveats
- explicit types: emplace can surprise—keep intent obvious
- initializer_list ambiguity with vector<vector
>—prefer clarity
Related reading
- Move semantics
- Performance optimization
Keywords
emplace_back, push_back, in-place construction, C++ vector
Related posts
- Browse the C++ series
- C++ Adapter Pattern