文章来源:https://blog.youkuaiyun.com/u011068702/article/details/64443949
案例1:
#include <iostream>
#include <string>
using namespace std;
void PrintStr(std::string &str)
{
cout << str <<end;
}
void f(int &a)
{
cout << a << endl;
}
int main()
{
PrintStr(string("HelloWorld"));
int a =1,b=3;
f(a+b);
return 0;
}
int& g2(int *p) //
{
*p = 100;
return *p;
}
案例2
#include "stdio.h"
#include <iostream>
using namespace std;
int g1(int *p)
{
*p = 100;
return *p;
}
int main()
{
int a1 = 10;
a1 = g1(&a1);
int &a2 = g1(&a1);
printf("a1:%d \n", a1);
printf("a2:%d \n", a2);
return 0;
}
都会报错: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
原因分析:
案例1:就拿f(a + b)来说,a+b的值会存在一个临时变量中,当把这个临时变量传给f时,由于f的声明中,参数是int&,不是常量引用,因为c++编译器的一个关于语义的限制。如果一个参数是以非const引用传入,c++编译器就有理由认为程序员会在函数中修改这个值,并且这个被修改的引用在函数返回后要发挥作用。但如果你把一个临时变量当作非const引用参数传进来,由于临时变量的特殊性,程序员并不能操作临时变量,而且临时变量随时可能被释放掉,所以,一般说来,修改一个临时变量是毫无意义的,据此,c++编译器加入了临时变量不能作为非const引用的这个语义限制。
案例2:int g1(int *p) 返回的也是一个临时变量。
解决方案:
案例1,可在参数前加入const
#include <iostream>
#include <string>
using namespace std;
void PrintStr(const std::string &str)
{
cout << str <<endl;
}
void f(const int &a)
{
cout << a << endl;
}
int main()
{
PrintStr(string("HelloWorld"));
int a =1,b=3;
f(a+b);
return 0;
}
或者改变赋值方法:
#include <iostream>
#include <string>
using namespace std;
void PrintStr(std::string &str)
{
cout << str <<endl;
}
void f(int &a)
{
cout << a << endl;
}
int main()
{
string str = "HelloWorld";
PrintStr(str);
int a =1,b=3;
int c = a+b;
f(c);
return 0;
}
案例2:
函数返回值返回对象本身,不产生临时变量:
int& g2(int *p)
{
*p = 100;
return *p;
}
总结:
c++中临时变量不能作为非const的引用参数