简体   繁体   English

c ++:函数左值或右值

[英]c++: function lvalue or rvalue

I just started learning about rvalue references in c++11 by reading this page , but I got stuck into the very first page. 我刚开始通过阅读本页来了解c ++ 11中的右值引用,但我陷入了第一页。 Here is the code I took from that page. 这是我从该页面获取的代码。

  int& foo();
  foo() = 42; // ok, foo() is an lvalue
  int* p1 = &foo(); // ok, foo() is an lvalue

  int foobar();
  j = foobar(); // ok, foobar() is an rvalue
  int* p2 = &foobar(); // error, cannot take the address of an rvalue
  1. why is foo() an lvalue? 为什么foo()是一个左值? is it because foo() returns int& which is basically an lvalue? 是因为foo()返回int&它基本上是一个左值?
  2. why is foobar() an rvalue? 为什么foobar()是右值? is it because foobar() returns int ? 是因为foobar()返回int
  3. In general, why would you care if a function is an rvalue or not? 一般来说,为什么你会关心函数是否是右值? I think if I read the rest of that article, I'll get my answer to this. 我想如果我读完那篇文章的其余部分,我会得到答案。

L-Values are locations, R-Values are actual values. L值是位置,R值是实际值。

So: 所以:

  1. since foo() returns a reference( int& ), that makes it an lvalue itself. 因为foo()返回一个引用( int& ),这使得它本身就是一个左值。
  2. Correct. 正确。 foobar() is an rvalue because foobar() returns int . foobar()是一个右值,因为foobar()返回int
  3. We don't care that much if a function is an R-Value or not. 如果函数是否是R值,我们并不在意。 What we are getting excited about is R-Value references. 我们感到兴奋的是R值参考。

The article you pointed to is interesting and I had not considered forwarding or the use in factories before. 您指出的文章很有趣,我以前没有考虑转发或在工厂中使用。 The reason I was excited about R-Value references was the move semantics, such as this: 我对R值引用感到兴奋的原因是移动语义,例如:

BigClass my_function (const int& val, const OtherClass & valb);

BigClass x;
x = my_function(5, other_class_instance);

In that example, x is destroyed, then the return of my_function is copied into x with a copy constructor. 在该示例中,x被销毁,然后使用复制构造函数将my_function的返回复制到x中。 To get around that historically, you would write: 为了在历史上解决这个问题,你会写:

void my_function (BigClass *ret, const int& val, const OtherClass & valb);

BigClass x;
my_function(&x, 5, other_class_instance);

which means that now my_function has side effects, plus it isn't as plain to read. 这意味着现在my_function有副作用,而且它不是那么简单。 Now, with C++11, we can instead write: 现在,使用C ++ 11,我们可以改为:

BigClass & my_function (const int& val, const OtherClass & valb);

BigClass x;
x = my_function(5, other_class_instance);

And have it operate as efficiently as the second example. 并使其运行与第二个例子一样有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM