当我在C ++中给一个const引用赋值一个临时int时会发生什么? [英] What happens when I assign a temporary int to a const reference in C++?

查看:104
本文介绍了当我在C ++中给一个const引用赋值一个临时int时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


假设我有一个函数 f




b $ b

  int f(int x){return x;} 

const int& a = f(1)

我知道 f(1)只是一个临时的,我会被破坏后这个语句,但


  1. 做引用const会给f(1)一个长寿命吗?

  2. 如果是,其中 f(1)将被存储?

  3. 这意味着 x 在范围外时也不会被销毁?

  4. f(1) x


解决方案

您将表达式与值混淆。



1)由表达式返回的临时值的生命周期 f(1)将有其生存期延长。这个规则对于 const 引用是唯一的。



2)编译器想要的,但可能在堆栈上。 / p>

3)也许。它取决于编译器是复制 x 还是执行复制elision。因为类型是 int ,所以没关系。



4)有很多差异。一个是 int f(int)中的局部变量的名称。这是一个左值。另一个是调用 int f(int)并求值为右值的表达式。


Possible Duplicate:
Does a const reference prolong the life of a temporary?

let say that I have a function f:

int f(int x){return x;}

const int &a=f(1);

I know that f(1) is just a temporary and i will be destroyed after this statement, but

  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) 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) Anywhere the compiler wants, but probably on the stack.

3) Maybe. It depends on whether the compiler copied x or performed copy elision. Since the type is int, it doesn't matter.

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.

这篇关于当我在C ++中给一个const引用赋值一个临时int时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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