samedi 27 juin 2020

Why does the following code not result in moving the object instead of copying?

class A
{
public:
   A() { std::cout << "a ctor\n"; }
   A(const A&) { std::cout << "a copy ctor\n"; }
   A(A&&) { std::cout << "a move ctor\n"; }
};


A f(int i)
{
   A a1;
   return i % 2 == 0 ? a1 : A{};
}

int main()
{
   f(5);
   return 0;
}

The output is:

a ctor

a copy ctor

I would expect that a1 in f() will be moved not copied. If I change f() just a little bit, it's not a copy anymore but a move:

A f(int i)
{
   A a1;
   if (i % 2 == 0)
   {
      return a1;
   }
   return A{};
}

Could you explain me how does this work?

Aucun commentaire:

Enregistrer un commentaire