为何非const左值引用无法绑定右值?C++编译报错解析
非const左值引用绑定右值的编译错误解释
问题代码
#include <string> #include <iostream> using std::string; using std::cout; using std::endl; void modify_nd_print_string(string&); int main (){ auto s = ""; modify_nd_print_string(s); return 0; } void modify_nd_print_string(string& s){ s.clear(); s = "test"; cout << s << endl; return; }
编译错误信息
main.cpp: In function ‘int main()’: main.cpp:11:25: error: cannot bind non-const lvalue reference of type ‘std::__cxx11::string&’ {aka ‘std::__cxx11::basic_string<char>&’} to an rvalue of type ‘std::__cxx11::string’ {aka ‘std::__cxx11::basic_string<char>’} modify_nd_print_string(s); ^ compilation terminated due to -Wfatal-errors.
错误原因解释
你误解了main中s的实际类型:
""是C风格字符串字面量,类型为const char[1]。使用auto s = "";时,编译器会将s推导为const char*,而非你预期的std::string。- 当你把
const char*类型的s传入modify_nd_print_string(string&)时,编译器会尝试隐式创建一个临时的std::string对象(将const char*转换为std::string),这个临时对象属于右值。 - C++语法规定,非const的左值引用(
string&)不能绑定到右值临时对象,因此触发编译错误。
解决方法
要让s成为std::string类型的左值,只需显式指定类型或引导auto推导正确类型:
- 方法一:显式声明类型
std::string s = "";
- 方法二:用
std::string构造式引导auto推导
auto s = std::string("");
内容的提问来源于stack exchange,提问作者Vinod
相关产品推荐
相关产品推荐

