Unary + on pointers

前端 未结 3 708
春和景丽
春和景丽 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).

提交回复
热议问题