gpt4 book ai didi

c++ - 通过引用传递和返回参数时的整体提升?

转载 作者:太空狗 更新时间:2023-10-29 23:42:37 25 4
gpt4 key购买 nike

我正在阅读一些关于重载决议的内容,我发现了一些困扰我的事情......在下面的代码中:

int const& MaxValue(int const& a, int const& b)
{
return a > b ? a : b;
}

void SomeFunction()
{
short aShort1 = 3;
short aShort2 = 1;
int const & r2 = MaxValue(aShort1, aShort2); // integral promotion
//is it safe to pass r2 around before function SomeFunction completes
// CallSomeOtherFunctionThatCallsSomethingElse(r2);

}

我的理解是创建了两个临时 int,并将它们分配到属于 SomeFunction 的堆栈上。因此,当 MaxValue 返回时,r2 引用这些临时变量之一(在本例中,值为 3 的变量)。因此,传递 r2 应该是安全的。

问题是,如果我的理解没问题,这是标准行为吗(请验证)?如果不是,请解释上面代码中发生了什么。

非常感谢

最佳答案

欢迎了解为什么隐式转换很糟糕。您现在有一个对临时文件的引用,它已被销毁。希望你不想用它做任何事情。

关于c++ - 通过引用传递和返回参数时的整体提升?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3175055/

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