Is an object guaranteed to be moved when it is returned?

前端 未结 3 405
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 15:21

I know that when passing an object by value to a function, the move constructor is always called if there is one, assuming no copy elision. What about returning an object by

3条回答
  •  伪装坚强ぢ
    2020-12-05 16:12

    In this case, since the return value has a name (f), it would be NRVO (named return value optimization) that would apply.

    So, the technical answer based only on wording, is that the absence of RVO won't prevent copy elision, since NRVO could still allow it.

    Past that, I believe the selection between move/copy of the return value can/will depend on the definition of Foo -- there are definitely times it'll be copied instead of moved, such as if you've explicitly deleted the move constructor and move assignment operators, or you haven't defined move construction/assignment, and it isn't eligible for them being synthesized implicitly.

    Edit: [responding to edited question]: Having a move constructor still doesn't guarantee that the result will be moved. One obvious example would be if you had deleted the move assignment operator, and were assigning the result (rather than using it to initialize). In this case, the deleted move assignment operator would prevent moving the return value.

    To answer what you may have been getting at, though, the general rule is that moving will be done if possible, and it'll fall back to copying if and only if something prevents the result from being moved.

提交回复
热议问题