是否允许 C++ 编译器仅用构造替换 construct + moveconstruct?

Are C++ compilers allowed to replace construct + moveconstruct with just a construct?

是否允许 C++ 编译器替换:

const auto myType = MyType(1, 2, 3);

与:

const MyType myType(1, 2, 3);

即发出赋值,或者有什么可以阻止这种情况?

注: 我问的原因是我更喜欢第一个版本

是的,一个实现可以省略 copy/move class 的构造 当满足某些条件时对象,它被称为 copy elision.

Under the following circumstances, the compilers are permitted to omit the copy- and move-constructors of class objects even if copy/move constructor and the destructor have observable side-effects.

对于您的代码,

If a function returns a class type by value, and the return statement's expression is the name of a non-volatile object with automatic storage duration, which isn't the function parameter, or a catch clause parameter, and which has the same type (ignoring top-level cv-qualification) as the return type of the function, then copy/move is omitted. When that local object is constructed, it is constructed directly in the storage where the function's return value would otherwise be moved or copied to. This variant of copy elision is known as NRVO, "named return value optimization".

请注意,copy/move 构造函数仍然需要可访问。

Even when copy elision takes place and the copy-/move-constructor is not called, it must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed.