What happens when I assign a temporary int to a const reference in C++?(当我将临时 int 分配给 C++ 中的 const 引用时会发生什么?)
问题描述
可能重复:
const 引用会延长临时对象的寿命吗?
假设我有一个函数 f
:
int f(int x){return x;}
const int &a=f(1);
我知道f(1)
只是暂时的,在这个语句之后i会被销毁,但是
I know that f(1)
is just a temporary and i will be destroyed after this statement, but
- 将引用设为 const 是否会使 f(1) 寿命更长?
- 如果是,
f(1)
将存储在哪里? - 这是否意味着
x
在超出范围时也不会被销毁? f(1)
和x
有什么区别?
- does making the reference const will give f(1) a long life ?
- if yes, where
f(1)
is gonna be stored ? - and is that mean that
x
also did not get destroyed when it run out of scope? - what is the difference between
f(1)
andx
?
推荐答案
你把表达式和值混淆了.
You're confusing expressions with values.
1) 表达式 f(1)
返回的临时值的生命周期将延长其生命周期.此规则对于 const
引用是唯一的.
1) The lifetime of the temporary value returned by the expression f(1)
will have its lifetime extended. This rule is unique for const
references.
2) 编译器想要的任何位置,但可能在堆栈上.
2) Anywhere the compiler wants, but probably on the stack.
3) 也许.这取决于编译器是复制 x
还是执行复制省略.由于类型是int
,所以没关系.
3) Maybe. It depends on whether the compiler copied x
or performed copy elision. Since the type is int
, it doesn't matter.
4) 差异很大.一个是 int f(int)
内的局部变量的名称.它是一个左值.另一个是调用 int f(int)
并计算为右值的表达式.
4) Lots of differences. One is the name of a local variable inside int f(int)
. It is an lvalue. The other is an expression which calls int f(int)
and evaluates to an rvalue.
这篇关于当我将临时 int 分配给 C++ 中的 const 引用时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当我将临时 int 分配给 C++ 中的 const 引用时会发生什么?


- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01