C++ 对象构造——直接初始化与使用“=”运算符,它们是等价的吗?
C++ object construction -- direct initialization versus using the '=' operator, are they equivalent?
在 C++ 中,这两种初始化 class 对象的方式在功能上是等效的,还是在某些情况下它们可能具有不同的语义并生成不同的代码?
SomeClass foo(1,2,3);
对
auto foo = SomeClass(1,2,3);
第二个是copy initialization,在概念上foo
是从直接初始化的临时SomeClass
复制初始化的。 (顺便说一句,它与 operator=
无关;它是初始化而不是赋值。)
因为 mandatory copy elision (C++17 起) 它们具有完全相同的效果,对象由适当的构造函数直接初始化。
In the initialization of an object, when the initializer expression is
a prvalue of the same class type (ignoring cv-qualification) as the
variable type:
T x = T(T(f())); // only one call to default constructor of T, to initialize x
在C++17之前复制省略是一种优化;即使 copy/move 结构也可能被省略,适当的 copy/move 构造函数必须可用;如果不是(例如,构造函数被标记为 explicit
),则第二个样式将不起作用,而第一个样式可以。
This is an optimization: even when it takes place and the copy/move (since C++11)
constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed:
在 C++ 中,这两种初始化 class 对象的方式在功能上是等效的,还是在某些情况下它们可能具有不同的语义并生成不同的代码?
SomeClass foo(1,2,3);
对
auto foo = SomeClass(1,2,3);
第二个是copy initialization,在概念上foo
是从直接初始化的临时SomeClass
复制初始化的。 (顺便说一句,它与 operator=
无关;它是初始化而不是赋值。)
因为 mandatory copy elision (C++17 起) 它们具有完全相同的效果,对象由适当的构造函数直接初始化。
In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type:
T x = T(T(f())); // only one call to default constructor of T, to initialize x
在C++17之前复制省略是一种优化;即使 copy/move 结构也可能被省略,适当的 copy/move 构造函数必须可用;如果不是(例如,构造函数被标记为 explicit
),则第二个样式将不起作用,而第一个样式可以。
This is an optimization: even when it takes place and the copy
/move (since C++11)
constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed: