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

Viewed 6700

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 *?

1 Answers

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();
Related