简体   繁体   中英

Why does this code give the error “cannot bind non-const lvalue reference of type ‘char*&’ to an rvalue of type ‘char*’”

Why does the following code give this error:

cannot bind non-const lvalue reference of type 'char &' to an rvalue of type 'char '

#include <string>

int main()
{
    std::string p {"Test string"};
    auto &r = p.data();
    return 0;
}

The type of the pointer returned by std::string::data is char * . And the type of variable r is char *& . So why, in this case, the type of char * cannot be referenced by a type of char * ?

The reason is that the C++ standard doesn't allow non-const references to bind to temporaries, and std::string::data returns a pointer by value. Only const reference can do that, and prolong the life of the temporary object.

In your case you either need to make your reference const.

const auto& r = p.data();

Or better, just create a variable that will store the pointer for you, as pointers are cheap to copy around.

const char* r = p.data();

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