简体   繁体   中英

Why are string literals not rvalues

Consider this code:

void test(auto& arg){}

int main(){
    test("bla");
    test(1);
}

The call test(1); gives an error, because 1 is an rvalue

main.cpp: In function 'int main()':
main.cpp:50:14: error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'
   50 |         test(1);
      |              ^
main.cpp:37:17: note:   initializing argument 1 of 'void test(auto:1&) [with auto:1 = int]'
   37 | void test(auto& arg){}

Why isn't this the case for test("bla"); ? Shouldn't this be an r-value as well?

test("bla");

The type of this string literal is const char[4]

So you were actually calling:

void test(const char (&arg)[4]){}

The arg is const-qualified here, so if you change arg in this function body, you will also get a compile error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM