Reputation: 429
A Function1()
{
return {1};
}
A Function2()
{
return A{1};
}
A Function3()
{
A a{1};
return a;
}
i tried three ways. they all call just one assignment constructor.
i question There can be performance difference depending on which complier to use?
Upvotes: 1
Views: 78
Reputation: 217085
There are subtle differences:
Function1
requires non explicit A
's constructor.
construct A
"in place" (even before C++17). so copy/move A's constructor might even be marked as = delete
, and program is well formed.
pre-C++17, Function2
will use move/copy constructor which might be elided (return value optimization: RVO) (copy/move constructor should be available though (marking as = delete
won't compile)).
Post C++17, no move/copy are done (similar to Function1
, but work with explicit
constructors).
Function3
will use move/copy constructor which might be elided (named return value optimization: NRVO).
With correct options, compilers will do the optimization, and all should be equivalent.
With options such as -fno-elide-constructors
, pre-c++17, Function1
should win, post C++17, Function1
and Function2
should win.
Upvotes: 5
Reputation: 67362
The first two are identical, they will construct and return the object using A(1)
.
The last one, without NRVO, will create the object on the stack then copy-construct it to return. With NRVO it should be the same as the other two.
Upvotes: 3