传递常量引用......它是否像最重要的const一样工作? [英] Passing constant reference... does it work like most important const?
本文介绍了传递常量引用......它是否像最重要的const一样工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个已知的特殊情况, int MyFunction()
{
int x = 5;
return x;
}
int main()
{
const int& y = MyFunction();
std :: cout<< 这是有效的:<<的std :: ENDL;
返回0;
$ / code>
现在,如果我有以下两个函数:
int MyFunction()
{
int x = 5;
return x;
}
void MyOtherFunction(const int& val)
{
std :: cout<< val<<的std :: ENDL;
}
int main()
{
MyOtherFunction(MyFunction());
}
这是否符合标准?什么是传递const引用的限制?
解决方案
这也没问题:标准要求匿名临时( MyFunction()
)可以绑定到一个const引用。
(它不能绑定到非const引用;有些编译器会失效)。
It's a known special case that constant references are not lost in return values if they're assigned as constant references:
int MyFunction()
{
int x = 5;
return x;
}
int main()
{
const int& y = MyFunction();
std::cout << "This is valid: " << std::endl;
return 0;
}
Now if I have two functions like the following:
int MyFunction()
{
int x = 5;
return x;
}
void MyOtherFunction(const int& val)
{
std::cout << val << std::endl;
}
int main()
{
MyOtherFunction(MyFunction());
}
Does this work according to the standard? What are the limitations of passing const references?
解决方案
That's fine too: the standard mandates that an anonymous temporary (MyFunction()
)can bind to a const reference.
(It can't bind to a non-const reference; some compilers are lapse on that).
这篇关于传递常量引用......它是否像最重要的const一样工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文