当我将临时 int 分配给 C++ 中的 const 引用时会发生什么? [英] What happens when I assign a temporary int to a const reference in C++?

查看:25
本文介绍了当我将临时 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

  1. 将引用设为 const 是否会使 f(1) 寿命更长?
  2. 如果是,f(1) 将存储在哪里?
  3. 这是否意味着 x 在超出范围时也不会被销毁?
  4. f(1)x有什么区别?
  1. does making the reference const will give f(1) a long life ?
  2. if yes, where f(1) is gonna be stored ?
  3. and is that mean that x also did not get destroyed when it run out of scope?
  4. what is the difference between f(1) and x?

推荐答案

你把表达式和值混淆了.

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 引用时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆