Unary + on pointers

前端 未结 3 707
春和景丽
春和景丽 2021-02-19 18:49

I was just browsing through the draft of the C++11 standard and found the following puzzling statement (§13.6/8):

For every type T there exist c

相关标签:
3条回答
  • 2021-02-19 19:34

    The + on pointers is a noop except for turning things to rvalues. It sometimes is handy if you want to decay arrays or functions

    int a[] = { 1, 2, 3 };
    auto &&x = +a;
    

    Now x is an int*&& and not an int(&)[3]. If you want to pass x or +a to templates, this difference might become important. a + 0 is not always equivalent, consider

    struct forward_decl;
    extern forward_decl a[];
    auto &&x = +a; // well-formed
    auto &&y = a + 0; // ill-formed
    

    The last line is ill-formed, because adding anything to a pointer requires the pointer's pointed-to class type to be completely defined (because it advances by sizeof(forward_decl) * N bytes).

    0 讨论(0)
  • 2021-02-19 19:42

    Well, you could overload it do do whatever you want, but it's just there for symmetry with the unary - operator. As you mention, it's just a no-op most of the time.

    0 讨论(0)
  • 2021-02-19 19:50

    The answer to your question is just a page above the quote you cited — §13.6/1:

    The candidate operator functions that represent the built-in operators defined in Clause 5 are specified in this subclause. These candidate functions participate in the operator overload resolution process as described in 13.3.1.2 and are used for no other purpose. [ Note: Because built-in operators take only operands with non-class type, and operator overload resolution occurs only when an operand expression originally has class or enumeration type, operator overload resolution can resolve to a built-in operator only when an operand has a class type that has a user-defined conversion to a non-class type appropriate for the operator, or when an operand has an enumeration type that can be converted to a type appropriate for the operator. Also note that some of the candidate operator functions given in this subclause are more permissive than the built-in operators themselves. As described in 13.3.1.2, after a built-in operator is selected by overload resolution the expression is subject to the requirements for the built-in operator given in Clause 5, and therefore to any additional semantic constraints given there. If there is a user-written candidate with the same name and parameter types as a built-in candidate operator function, the built-in operator function is hidden and is not included in the set of candidate functions. —end note ]

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