On May 20, 8:08 am,
peter.kub...@gmail.com wrote:
> Hi!
>
> The output of the example below is "CopyMove". Should not it be
> "MoveMove" ? If not, why is it so ? I tried this with GCC 4.7, VS
> 10, and VS11 Beta. All the compilers return "CopyMove".
In a situation when function returns an object of the same type as the
return type, compiler follows three step procedure: 1) elide copy on
return; if can't 2) move on return; if can't 3) copy on return. This
is probably the only situation (a similar case when throwing an
object) when compiler is allowed to move from lvalue. On the other
hand, when compiler returns an expression, it's up to optimizer to
figure out the best way following as if rule.
> Thank you very much for the answer.
>
> PK.
>
> // ---
> #include <iostream>
> #include <cstdlib>
> using namespace std;
> struct CBigData
> {
> CBigData() {}
> CBigData(const CBigData &)
> {
> cout << "Copy";
> }
> CBigData(CBigData &&)
> {
> cout << "Move";
> }
>
> };
>
> CBigData MoveTest()
> {
> CBigData b1, b2;
> return rand() % 2 ? b1 : b2;
>
> }
This returns an expression, b1 and b2 are lvalues, they cannot be
moved from, so compiler uses copy.
> CBigData MoveTest2()
> {
> CBigData b1, b2;
> if (rand() % 2)
> return b1;
> else
> return b2;
>
> }
And this is the case of returning an object, compiler is allowed to
elide copy or move from lvalue on return.