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

标签 c++ function reference constants

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

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/

相关文章:

c++ - 如何使用 chrono 为带有累加器计时器的算法计时?

c++ pragma #error 报错

c++ - 检查数组中复合图形的最大公约数的函数

c - 在函数 C 中访问数组

mysql - 如何在 MySQL 中将一个数字与一个单词连接起来?

C++11 多线程,通过引用传递

javascript - 服务中的 Angular 引用错误

c# - 直接访问变量(而不是使用指针和解引用器)可以给出不同的值吗?

python - 基于条件的 Pandas 数据框计算

c++ - 函数的返回值未被识别为左值