Since a string literal is considered an lvalue, why must the binding lvalue reference be const?

前端 未结 3 678
灰色年华
灰色年华 2021-02-19 05:42

I know there are topics that are similar to this one already (such as this).

The example given in this topic was this:

std::string & rs1 = std::strin         


        
3条回答
  •  无人共我
    2021-02-19 06:37

    First, a string is a const char * or const char [N] not a std::string. So you're not directly assigning those char * strings. std::string has a constructor that takes a const char [N] and the compiler automatically uses it to construct a new instance.

    But when using const for s2 you've just made it impossible for the compiler to assign the new std::string instance to s2.

    So in the end I think you've misunderstood the difference between a "string" of type const char [N] and a "string" of type std::string. The standard is referring to const char [N] when it is talking about strings being an lvalue but you're attempting to apply that to a std::string to which the standard's rule doesn't apply.

提交回复
热议问题