左值引用和右值绑定

lvalue reference and rvalue binding

提问人:Vinod 提问时间:8/25/2023 更新时间:8/25/2023 访问量:42

问:

#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;
}

在上面的代码中,我使用参数类型是出于显而易见的原因:该方法修改了通过引用传递给它的字符串。string&modify_nd_print_string()

但是,我从编译器(g ++)收到以下错误:

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.

我不明白为什么传递给的参数被视为右值,而传递给函数的是左值?modify_nd_print_string()main()

有人可以解释一下吗?

短暂性投资安全

C++ 绑定 按引用传递

评论

2赞 273K 8/25/2023
s是,它不能绑定到,编译器试图将其转换为一个临时的右值,也不能绑定到。const char*string&std::string(s)string&
0赞 BoP 8/25/2023
此外,字符串不必由 显式启动,只需一个 will do。= ""string s;
0赞 Andrej Podzimek 8/25/2023
自动 s{“”s};std::string s;

答: 暂无答案