C++引用报错:invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type
2018-01-13 14:54
2371 查看
一、
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、看代码
2、编译结果
3、分析和解决
就拿f(a + b)来说,a+b的值会存在一个临时变量中,当把这个临时变量传给f时,由于f的声明中,参数是int&,不是常量引用,因为c++编译器的一个关于语义的限制。如果一个参数是以非const引用传入,c++编译器就有理由认为程序员会在函数中修改这个值,并且这个被修改的引用在函数返回后要发挥作用。但如果你把一个临时变量当作非const引用参数传进来,由于临时变量的特殊性,程序员并不能操作临时变量,而且临时变量随时可能被释放掉,所以,一般说来,修改一个临时变量是毫无意义的,据此,c++编译器加入了临时变量不能作为非const引用的这个语义限制。修改:
或则函数参数引用加上const
4、总结
c++中临时变量不能作为非const的引用参数
相关文章推荐
- C++引用报错:invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type
- invalid initialization of non-const reference of type ‘xxx&’ from an rvalue of type ‘xxx’
- C++之invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
- invalid initialization of non-const reference of type ‘int*&’ from a temporary of type ‘int*’
- error: invalid initialization of non-const reference of type ‘*&’ from a temporary of type
- invalid initialization of non-const reference of type ‘int*&’ from a temporary of type ‘int*’
- 编译错误:error: invalid initialization of non-const reference of type ‘*&’ from a temporary of type
- invalid initialization of non-const reference of type与discards qualifiers
- invalid initialization of non-const reference of type与discards qualifiers
- C++编译出现binding ‘const string {aka const std::__cxx11::basic_string<char>}’ to reference of type ‘std
- 问题解决:javax.servlet.jsp.el.ELException: The "." operator was supplied with an index value of type "java.lang.String" to be applie
- C++ Error : initial value of reference to non-const must be an lvalue
- The value of attribute "description" associated with an element type "target" must not contain the '<' character.
- terminate called after throwing an instance of 'std::logic_error' [aidl] what(): basic_string
- terminate called after throwing an instance of 'std::string'
- jsf配置问题 Error performing conversion of value ' of type class java.lang.String to type class
- A const field of a reference type other than string can only be initialized with null Error [duplicate]
- Bean property 'RegDao' is not writable or has an invalid setter method. Does the parameter type of t
- C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const std::basic
- ReactJs 报错 Element type is invalid: expected a string (from built-in components) or a class/function (for composite components) but got: undefined. Check the render method of `Me`.