Why can const char* const & = “hello” compile?

后端 未结 2 1856
Happy的楠姐
Happy的楠姐 2021-02-01 12:58

I am reading a code snippet from a book and find this:

const char* const & a = \"hello\"; //can compile 
const char*& a = \"hello\"; //cannot
         


        
2条回答
  •  一向
    一向 (楼主)
    2021-02-01 13:06

    It's essentially adhering to this formula

    T const & a = something_convertible_to_T;
    

    Where T is const char*. In the first case, a temporary pointer can be materialized, assigned the address of the literal, and then have itself bound to the reference. In the second case, since the lvalue reference isn't const, it can't happen. Another example of more of the same

    const char* && a = "hello"; // rvalue ref makes a no into a yes.
    

    Now the temporary pointer is bound to an rvalue reference.

提交回复
热议问题