RVO, move operations and a dilemma

前端 未结 1 1114
一整个雨季
一整个雨季 2021-02-15 16:41

I have been learning about move constructors over the last day or so, trying to stick to a general rule of returning by value as most people seem to suggest, and have come acros

相关标签:
1条回答
  • 2021-02-15 17:05

    The implicit move-on-return is only legal in the same contexts in which RVO is legal. And RVO is legal when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv- unqualified type as the function return type ([class.copy]/p31/b1).

    If you transform make_c4 to:

    C make_c4(int a) {
        C tmp;
        if (a == 1)
            return make_c1();
        return tmp;
    }
    

    Then you get the expected move construction for the call to make_c4(2). Your make_c5 rewrite is not desirable for exactly the reasons you state.

    Update:

    I should have also included a reference to [expr.cond]/p6/b1 which explains the semantics of the conditional expression when the second expression is a prvalue and the third is an lvalue, but both have the same type:

    The second and third operands have the same type; the result is of that type. If the operands have class type, the result is a prvalue temporary of the result type, which is copy-initialized from either the second operand or the third operand depending on the value of the first operand.

    I.e. this paragraph specifies that the resultant prvalue of the conditional is copy-initialized, from the 3rd argument in your example. Copy-initialization is defined in [dcl.init]/p14. When the source of a copy-initialization is a class-type lvalue, this will invoke the type's copy constructor. If the source is an rvalue, it will invoke the move constructor if one exists, else it will invoke the copy constructor.

    The specification of the conditional expression has no allowance for an implicit move from an lvalue argument, even if the conditional expression is part of a return expression. It is possible that the language could have been crafted to allow such an implicit move, but as far as I know, it was never proposed. Furthermore the existing specification of the conditional expression is already extremely complicated, making such change to the language all the more difficult.

    0 讨论(0)
提交回复
热议问题