一、

invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type ‘std::string’

#include<iostream>
#include<string>
using std::cout;
using std::string;
using std::endl;
void PrintStr(std::string& str);
int main()
{
    PrintStr(string("HelloWorld!"));   //string("HelloWorld!")  为一个临时变量
    return 0;
}
void PrintStr(std::string& str)
{
    cout<< str << endl;
}
说明:临时变量是转瞬即逝的,在上面的代码中,用str引用临时变量的时候临时变量已经不存在了。

解决方案:void PrintStr(std::string& str);改为void PrintStr(const std::string& str);

二、

1、看代码

C++引用报错:invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type



2、编译结果

C++引用报错:invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type



3、分析和解决

就拿f(a + b)来说,a+b的值会存在一个临时变量中,当把这个临时变量传给f时,由于f的声明中,参数是int&,不是常量引用,因为c++编译器的一个关于语义的限制。如果一个参数是以非const引用传入,c++编译器就有理由认为程序员会在函数中修改这个值,并且这个被修改的引用在函数返回后要发挥作用。但如果你把一个临时变量当作非const引用参数传进来,由于临时变量的特殊性,程序员并不能操作临时变量,而且临时变量随时可能被释放掉,所以,一般说来,修改一个临时变量是毫无意义的,据此,c++编译器加入了临时变量不能作为非const引用的这个语义限制。

修改:

C++引用报错:invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type


或则函数参数引用加上const


C++引用报错:invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type



4、总结

c++中临时变量不能作为非const的引用参数 


相关文章:

  • 2022-12-23
  • 2021-05-25
  • 2021-04-14
  • 2021-11-10
  • 2021-11-16
  • 2021-06-08
  • 2022-01-18
猜你喜欢
  • 2021-09-16
  • 2021-10-26
  • 2022-12-23
  • 2022-12-23
  • 2021-06-15
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案