Why can I use initializer lists on the right-hand side of operator += but not operator+?

后端 未结 3 1589
遇见更好的自我
遇见更好的自我 2021-01-03 20:15

This is a follow-up to an earlier question about why I can\'t use a brace-enclosed initializer as an argument to operator+, which was resolved by looking at this earlier que

相关标签:
3条回答
  • 2021-01-03 20:35

    += operator is a compound assignment. The standard explicitly permits initializer lists on the right-hand side of assignments:

    §8.5.4/1 [...] Note: List-initialization can be used

    ...

    — on the right-hand side of an assignment (5.17)

    §5.17 talks about all assignments, including compound ones:

    assignment-expression:
    - conditional-expression
    - logical-or-expression assignment-operator initializer-clause
    - throw-expression

    assignment-operator: one of
    = *= /= %= += -= >>= <<= &= ˆ= |=

    0 讨论(0)
  • 2021-01-03 20:39

    It is explained in the answer to this question (which is linked from the question you linked to).

    The language grammar only allows a braced list in certain grammatical contexts, not in place of an arbitrary expression. That list includes the right-hand side of assignment operators, but NOT the right-hand side of operators in general.

    += is an assignment operator, + is not.

    The grammar for assignment expressions is:

      assignment-expression:
         conditional-expression
         logical-or-expression assignment-operator initializer-clause
         throw-expression
      assignment-operator: one of
          = *= *= /= %= += -= >>= <<= &= ^= |=
      

    0 讨论(0)
  • 2021-01-03 20:43

    C++14 §5.17/9:

    A braced-init-list may appear on the right-hand side of

    • an assignment to a scalar, in which case the initializer list shall have at most a single element. The meaning of x={v}, where T is the scalar type of the expression x, is that of x=T{v}. The meaning of x={} is x=T{}.
    • an assignment to an object of class type, in which case the initializer list is passed as the argument to the assignment operator function selected by overload resolution (13.5.3, 13.3).

    This applies to a+=b via its $5.7/7 equivalence to a=a+b (except that a is evaluated only once for +=). Put another way, due to a comment by M.M., because of the equivalence for the built-in operators += is regarded as an assignment operator, and not a special update operator. Hence the quoted text above about “assignment” applies to +=.

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