error: invalid initialization of non-const reference of type ‘int&‘ from an rvalue of type ‘int‘

先看代码

#include<iostream>
int output(int &a)
{
	return a;
}
int test()
{
	int a(10);
	return a;
}

int main()
{
	std::cout << output(test()) << std::endl;
}

这段代码报了个error

error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'

然而把int output(int &a)改为int output(const int &a)却能通过编译并有输出

分析原因

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

总结

总的来说,临时值不能作为非常量引用参数进行传递

引用虽好,可不要乱传递哦


修改方案

方案一:

#include<iostream>
int output(int a) //不进行引用传递
{
	return a;
}
int test()
{
	int a(10);
	return a;
}

int main()
{
	std::cout << output(test()) << std::endl;
}

方案二:

#include<iostream>
int output(int& a)
{
	return a;
}
int test()
{
	int a(10);
	return a;
}

int main()
{
	int temp = test(); //将test的临时返回值由temp来接收,这样就把值的内容保存起来了
	std::cout << output(temp) << std::endl;
}

方案三:

#include<iostream>
int output(const int &a) // 将临时值作为常量引用传递,这样就不能进行修改
{
	return a;
}
int test()
{
	int a(10);
	return a;
}

int main()
{
	std::cout << output(test()) << std::endl;
}

引申

编译错误:int &x=10;

编译正确:const int &x=10;

//10在这里是临时值

(67条消息) error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'_南极墨白的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/tjcwt2011/article/details/121807151