[2026] C++ Copy Initialization | The `= expr` Form
이 글의 핵심
Copy initialization uses `T x = expr`. Differs from direct and list initialization; explicit constructors excluded; RVO and elision often remove actual 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.
아래 코드는 cpp를 사용한 구현 예제입니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
// 변수 선언 및 초기화
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
아래 코드는 cpp를 사용한 구현 예제입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며, 에러 처리를 통해 안정성을 확보합니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
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
아래 코드는 cpp를 사용한 구현 예제입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며, 에러 처리를 통해 안정성을 확보합니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
class FileHandle {
public:
explicit FileHandle(const std::string& path) {}
};
// FileHandle f = "data.txt"; // error
FileHandle f{"data.txt"};
Non-copyable types
아래 코드는 cpp를 사용한 구현 예제입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며, 에러 처리를 통해 안정성을 확보합니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
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. |