C++ Copy Initialization | The `= expr` Form
이 글의 핵심
Copy initialization is `T obj = v;`. It uses implicit conversion paths and cannot call explicit constructors—use direct init or braces when needed. Elision often removes copies.
What is copy initialization?
Copy initialization is the = expr form. It is related to but distinct from list initialization with {}. Move semantics and RVO/NRVO often eliminate the conceptual copy.
int x = 10;
std::string s = "Hi";
int y(10); // direct initialization
std::string s2("Hi"); // direct initialization
Why it exists:
- Familiar, assignment-like syntax
- C compatibility
- Implicit conversions allowed (when not blocked by
explicit)
Copy vs direct
class Widget {
public:
explicit Widget(int x) {}
};
// Widget w1 = 10; // error: explicit not allowed in copy-init
Widget w2(10);
Widget w3{10};
| Feature | Copy T x = v | Direct T x(v) / T x{v} |
|---|---|---|
explicit single-arg ctor from value | Not selected | Can be selected |
| Typical use | Readable “assign a value” | Explicit construction |
explicit and APIs
class FileHandle {
public:
explicit FileHandle(const std::string& path) {}
};
// FileHandle f = "data.txt"; // error
FileHandle f{"data.txt"};
Non-copyable types
class NonCopyable {
public:
NonCopyable(int x) {}
NonCopyable(const NonCopyable&) = delete;
};
// NonCopyable a = NonCopyable(10); // error
NonCopyable b(10);
Performance
Modern compilers elide copies in many copy-init scenarios; C++17 mandatory elision applies to certain prvalue patterns. Still watch implicit conversions that create temporaries.
Relationship to other forms
| Syntax | Category |
|---|---|
T x = v; | Copy initialization |
T x(v);, T x{v} | Direct initialization |
T x = {a,b} | Often copy-list / list rules |
If there is an =, the copy-init grammar is involved first.
FAQ
Q1: Definition?
A: = in a declaration—implicit conversions allowed unless explicit blocks them.
Q2: vs direct?
A: Direct init can use explicit ctors; copy init cannot from those contexts.
Q3: Performance?
A: Usually elided; profile if you have a reason to doubt.
Related: List initialization, Copy elision, RVO.
One line: Copy initialization is the = form—convenient, but explicit and overload rules differ from T x{...}.
Related posts
- C++ List initialization
- C++ Move semantics
- C++ RVO/NRVO
Keywords
C++, copy initialization, direct initialization, explicit, RVO.
More links
- C++ Default initialization
- C++ Aggregate initialization