简体   繁体   English

为什么此代码会给出错误“无法将 'char*&' 类型的非 const 左值引用绑定到 'char*' 类型的右值”

[英]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.

相关问题 无法将类型的非常量左值引用绑定到类型的右值 - cannot bind non-const lvalue reference of type to an rvalue of type 错误:无法将“bool&amp;”类型的非常量左值引用绑定到“bool”类型的右值 - error: cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type ‘bool’ 错误:无法将“int&amp;”类型的非常量左值引用绑定到“int”类型的右值 - Error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’ 错误:无法将“Position&amp;”类型的非常量左值引用绑定到“Position”类型的右值 - error: cannot bind non-const lvalue reference of type ‘Position&’ to an rvalue of type ‘Position’ 为什么定义复制构造函数会给我错误:无法将“obj&amp;”类型的非常量左值引用绑定到“obj”类型的右值? - Why defining copy constructor gives me error: cannot bind non-const lvalue reference of type 'obj&' to an rvalue of type 'obj'? 无法将“Node&”类型的非常量左值引用绑定到“const Node”类型的右值 - cannot bind non-const lvalue reference of type 'Node&' to an rvalue of type 'const Node' 类型的非常量左值引用无法绑定错误 - non-const lvalue reference to type cannot bind error 无法将“int&”类型的非常量左值引用绑定到“int”类型的右值 - cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int' 类型“”的非常量左值引用不能绑定到类型“ *”的临时对象 - non-const lvalue reference to type '' cannot bind to a temporary of type ' *' 从&#39;const char *&#39;类型的右值初始化&#39;const char *&&#39;类型的非const引用的无效初始化 - invalid initialization of non-const reference of type 'const char*&' from an rvalue of type 'const char *'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM