2

Are C++ compilers allowed to replace:

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

with:

const MyType myType(1, 2, 3);

ie, emit the assignment, or is there anything which prevents this?

Note: The reason I ask is that I prefer the first version.

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
Viktor Sehr
  • 12,825
  • 5
  • 58
  • 90
  • Yes, thats what the compilers should do instead of creating a temporary and then calling a copy or move constructor. – Arunmu May 27 '16 at 09:09
  • The first syntax requires a non-explicit, non-deleted and accessible move-/copy-constructor (though it may change in the future). – Piotr Skotnicki May 27 '16 at 09:11
  • There's no assignment, this is initialization. And assuming the first one compiles, then yes the compiler can eliminate the temporary. This is called *copy elision*. – M.M May 27 '16 at 09:17

1 Answers1

5

Yes, an implementation is allowed to omit the copy/move construction of a class object when certain criteria are met, it's called 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.

And for your code,

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".

Note that the copy/move ctor still need to be accessible.

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405