当我将临时 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.
相关文章