gpt4 book ai didi

c++ - 传递常量引用...它是否像最重要的常量一样工作?

转载 作者:行者123 更新时间:2023-11-30 02:37:52 25 4
gpt4 key购买 nike

这是一个已知的特殊情况,如果将常量引用分配为常量引用,则常量引用不会在返回值中丢失:

int MyFunction()
{
int x = 5;
return x;
}

int main()
{
const int& y = MyFunction();
std::cout << "This is valid: " << std::endl;
return 0;
}

现在如果我有如下两个函数:

int MyFunction()
{
int x = 5;
return x;
}
void MyOtherFunction(const int& val)
{
std::cout << val << std::endl;
}

int main()
{
MyOtherFunction(MyFunction());
}

这是否符合标准?传递 const 引用有哪些限制?

最佳答案

是的。

[C++14: 12.2/5]: [..] A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call. [..]

关于c++ - 传递常量引用...它是否像最重要的常量一样工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31406495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com