You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何非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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 12:11:19