2

Consider the below code:

Bar my_f()
{
    Foo f{args,to,create,foo};
    Bar b{std::move(f),other,args}; //Is move here unnecessary?

    // code that does not use f;

    return b;
}

Is compiler required to check {code that does not use f} and automatically move f into b?

Marius Bancila
  • 15,632
  • 8
  • 47
  • 86
balki
  • 24,438
  • 28
  • 97
  • 142
  • It is very unlikely the compiler will move `f`. It may do something more efficient and easy to implement, as long as it follows the as-if rule. There's a duplicate somewhere. – juanchopanza May 07 '14 at 20:40
  • 1
    There is no guarantee that the compiler would do that...I doubt a compiler would do that automatically because it would break scoping rules. – IdeaHat May 07 '14 at 20:40

1 Answers1

5

The compiler will not automatically move the object into the constructor of Bar, just because f is not used afterwards. If you want to move f, either make it explicit with std::move(f) or remove the named variable:

Bar b{Foo{args, to, create, foo}, other, args}; // will automatically move (if possible)
nosid
  • 47,164
  • 13
  • 106
  • 134