Can we use the return value optimization when possible and fall back on move, not copy, semantics when not?

前端 未结 2 1403
情书的邮戳
情书的邮戳 2021-02-09 10:51

Is it possible to write C++ code where we rely on the return value optimization (RVO) when possible, but fall back on move semantics when not? For example, the following code c

2条回答
  •  一向
    一向 (楼主)
    2021-02-09 11:42

    When the expression in the return statement is a non-volatile automatic duration object, and not a function or catch-clause parameter, with the same cv-unqualified type as the function return type, the resulting copy/move is eligible for copy elision. The standard also goes on to say that, if the only reason copy elision was forbidden was that the source object was a function parameter, and if the compiler is unable to elide a copy, the overload resolution for the copy should be done as if the expression was an rvalue. Thus, it would prefer the move constructor.

    OTOH, since you are using the ternary expression, none of the conditions hold and you are stuck with a regular copy. Changing your code to

    if(b)
      return x;
    return y;
    

    calls the move constructor.

    Note that there is a distinction between RVO and copy elision - copy elision is what the standard allows, while RVO is a technique commonly used to elide copies in a subset of the cases where the standard allows copy elision.

提交回复
热议问题