[英]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 '
无法将“char &”类型的非常量左值引用绑定到“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 *
. std::string::data
返回的指针类型是char *
。 And the type of variable r
is char *&
.变量
r
的类型是char *&
。 So why, in this case, the type of char *
cannot be referenced by a type of char *
?那么为什么在这种情况下
char *
的类型不能被 char 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.原因是 C++ 标准不允许非常量引用绑定到临时对象,并且
std::string::data
按值返回指针。 Only const
reference can do that, and prolong the life of the temporary object.只有
const
引用可以做到这一点,并延长临时 object 的寿命。
In your case you either need to make your reference const.在您的情况下,您需要将参考设为 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.