In C++, are these two styles of initializing a class-object functionally equivalent, or are there some situations where they might have differing semantics and generate different code?
SomeClass foo(1,2,3);
vs
auto foo = SomeClass(1,2,3);
The 1st one is direct initialization.
The 2nd one is copy initialization, in concept foo
is copy-initialized from the direct-initialized temporary SomeClass
. (BTW it has nothing to do with operator=
; it's initialization but not assignment.)
Because of mandatory copy elision (since C++17) they have the same effect exactly, the object is initialized by the appropriate constructor directly.
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
Before C++17 copy elision is an optimization; even the copy/move construction might be omitted the appropriate copy/move constructor has to be usable; if not (e.g. the constructor is marked as explicit
) the 2nd style won't work while the 1st is fine.
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: