Constant as rvalue in C++(11)

前端 未结 4 1386
孤城傲影
孤城傲影 2021-02-20 13:33

Why const int is not an R-value in C++(11)? I thought that R-value was \'anything\' which cannot be on the left hand side and constants fulfil that

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-20 13:52

    The parameter type is an rvalue reference and the standard forbids initialization of an rvalue-reference with an lvalue of a "reference-related" type.

    8.5.3 References [dcl.init.ref ]

    ...

    5 ... If T1 is reference-related to T2 and the reference is an rvalue reference, the initializer expression shall not be an lvalue.

    Hence, the following is an error:

    void f (long &&);
    
    const long x = 1;
    void g () { f (x); }
    

    But the following is not:

    void f (long &&);
    
    const int x = 1;
    void g () { f (x); }
    

    So, the reason for the error is not simply "the initialization is not with an rvalue", but because "the initialization is with an lvalue of a reference-related type."

提交回复
热议问题