gpt4 book ai didi

c++ - 对临时变量的 const 引用及其背后的机制

转载 作者:行者123 更新时间:2023-11-30 05:16:48 26 4
gpt4 key购买 nike

我已经阅读了很多关于 const 引用的文章,但没有找到我要找的东西。您能否纠正我关于将临时变量绑定(bind)到 const 引用以延长生命周期的机制的假设?

int Foo(){return 3;}

int main(){
const int& ref = Foo();
return 0;
}

Foo 返回一个临时的未命名值,该值位于寄存器中,通常随后会被忽略。将它绑定(bind)到 const 引用告诉编译器不要关闭它,而是将值保存在内存中,范围为 ref 和名为 ref 的别名。

这是它的工作原理吗?

最佳答案

Foo returns temporary unnamed value

正确。

that is located in a register

标准未指定。

and normally dismissed afterwards

在完整表达式的末尾销毁,更准确地说。如果生命周期没有被引用延长。

当然,整数没有析构函数,因此生命周期仅表示存储(如果有)是否可以重复使用。

Binding it to const reference tells the compiler not to dismiss it, but to save the value in memory with the scope of ref

正确。将引用绑定(bind)到临时对象会延长该临时对象的生命周期以匹配引用的生命周期。

关于c++ - 对临时变量的 const 引用及其背后的机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42467935/

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