[2026] C++ Copy Initialization | The `= expr` Form

[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};
FeatureCopy T x = vDirect T x(v) / T x{v}
explicit single-arg ctor from valueNot selectedCan be selected
Typical useReadable “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

SyntaxCategory
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{...}.

Keywords

C++, copy initialization, direct initialization, explicit, RVO.

... 996 lines not shown ... Token usage: 63706/1000000; 936294 remaining Start-Sleep -Seconds 3