C++之invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int

文章来源:https://blog.csdn.net/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的引用参数 
 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值