C ++中临时变量的用途是什么 [英] What is the use of temporaries in c++

查看:105
本文介绍了C ++中临时变量的用途是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友,

我对C ++中的临时功能有些怀疑.
我并不完全理解临时工的概念.我已经在google中搜索过,但是对此却没有任何令人满意的解释,最重要的是我们为什么使用它?所以,伙计们,请允许我给出一些很好的解释,并举例说明我很容易理解.

...等待您的回复...



问候.
Johny ...

Hi Friends,

I have some doubt in temporaries in C++.
I did not exactly understand the concept of temporaries. I already searched in google, but I did not get any satisfactory explanation of this and most importantly why we use this? So guys please let me give some good explanation with example for that i can understand easily.

...Waiting for your replies...



Regards.
Johny...

推荐答案

一种简单的调整"方法是考虑如何计算类似
的表达式
A simple way to "tune" on them is thinking on how compute an expression like
z = (a+b)*c;



c乘以什么?
"a+b的结果",但是它必须作为+的结果以某种方式存储,仅用于*进行计算的时间.

现在呢



What does multiply c?
"The result of a+b", but it has to be stored somehow as result of + just for the time neede to * to compute.

Now what about

z = operator*(operator+(a,b),c);



这与上面的相同:名为"operator+"的函数返回结果,
然后将其以临时值的形式传递给另一个函数-operator*(在这种情况下).

很像
z = f(g(a,b),c);

表示为



This is the same as above: the function named "operator+" return a result,
that is then passed to another function - operator*, in this case - in the form of a temporary value.

Much like
z = f(g(a,b),c);

expressed as

tmp = g(a,b);
z = f(tmp,c);



当然,这对临时对象不是完全详尽无遗,只是在必须存在临时对象的情况下对其进行想象.



Of course, this is not completely exhaustive about temporaries, but is just a way to imagine them in a case they have to come to existence.


临时对象称为rvalues,非临时对象称为rvalues左值.代码中的命名对象是左值,而作为(子)表达式结果的临时对象是临时对象-右值.例如(x + y)是一个右值,而(x)是一个左值.每个表达式都是左值或右值.您可以轻松地在两者之间进行区分:您无法获得指向右值的指针,因此在使用& x进行操作时无法说&(x + y). C ++ 11引入了一个非常酷的功能,即rvalue参考,可以更有效地处理临时对象.要阅读有关临时人员和C ++ 11的新功能的信息,请阅读这篇冗长但精湛的说明文章:
Temporaries are called rvalues and non-temporaries are called lvalues. Named objects in your code are lvalues, and temporary object that are the results of your (sub)expressions are temporary objects - rvalues. For example (x+y) is an rvalue and (x) is an lvalue. Every expression is either an lvalue or rvalue. You can easily distinguis between the two: you can not get a pointer to an rvalue so you can not say &(x+y) while you can do this with &x. The C++11 introduces a very cool feature to handle temporaries more efficiently, its the rvalue reference. To read about temporaries and this new C++11 feature read this lengthy but superb explaining article: http://blogs.msdn.com/b/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx[^]


这篇关于C ++中临时变量的用途是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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