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
  • 16,053
  • 9
  • 49
  • 91
balki
  • 26,394
  • 30
  • 105
  • 151
  • 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
  • 48,932
  • 13
  • 112
  • 139