函数中作为参数传递的右值被视为函数内的左值? [英] is rvalue passed as parameter treated as lvalue inside the function?

查看:303
本文介绍了函数中作为参数传递的右值被视为函数内的左值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个View和一个Shape类,其中View拥有其Shape对象。
我将其实现为unique_ptr的向量。
在函数View :: add_shape(std :: unique_ptr&& shape)中,我仍然需要在rvalue参数上使用std :: move进行编译。为什么? (使用GCC 4.8)

I have a View and a Shape class where the View "owns" its Shape objects. I am implementing this as a vector of unique_ptr. In the function View::add_shape(std::unique_ptr&& shape), I still need to use std::move on the rvalue parameter to make it compile. Why? ( using GCC 4.8 )

#include <memory>
#include <vector>
using namespace std;

class Shape { };
class View
{
  vector<unique_ptr<Shape>> m_shapes;
  public:
  void add_shape(unique_ptr<Shape>&& shape)
  { 
    m_shapes.push_back(std::move(shape));// won't compile without the std::move
  }
};


int main()
{
  unique_ptr<Shape> ups(new Shape);
  View v;
  v.add_shape(std::move(ups));
}


推荐答案

是的,右值引用来自该参数仅用于从调用者的角度选择该函数,其行为类似于该函数内部的左值引用。

Yes, the rvalue reference from the parameter is only used to select the function from the caller's perspective, it behaves like an lvalue reference inside the function.

原因是只允许您移动一个一次赋值,认为自动保持参数的右值性太危险。参数类型指示此函数接受一个右值,并通过提供实际移动该值的实现来潜在地使用它。通过重载此方法的版本,可以优先使用固定版本。或简单地说,函数需要一个右值。

The reason is that you are only allowed to move a value once and it was deemed too dangerous to keep the rvalue-ness of a parameter automatically. The parameter type indicates that this function accepts an rvalue and makes potentially use of this by providing an implementation that actually moves the value. By overloading this version of the method can be used in favor of the non-moving version. Or it simply says that the function requires an rvalue.

函数实现中发生的事情是另一回事。考虑这样的方法

What happens in the implementation of the function is another thing. Consider a method like

void add_shape_twice(unique_ptr<Shape>&& shape)
{ 
  m_shapes.push_back(shape);
  m_shapes.push_back(shape);
}

如果 shape 为参数将仍然是右值引用:您可能不小心将值移动了两次。由于在现实世界中函数可能更长,并且多次引用参数(显式地或在循环或包扩展中)是很常见的,因此出错的可能性非常大。

if shape as a parameter would remain an rvalue reference: You would have accidentally moved the value twice. Since in the real world functions may be longer and it's quite common to refer to the parameters multiple times (either explicitly or within a loop or pack expansion), the potential for errors would be enormous.

即使我们大家都知道它并且永远不会忘记它,这也意味着我们需要放弃rvalue-ness,这会使代码变得很笨拙。我们会不断添加并删除 rvalue-ness。

Even if we would all be aware of it and never forget about it, it would also mean that we need to cast away rvalue-ness and this would make the code quite clumsy. We would constantly be adding and removing rvalue-ness.

这篇关于函数中作为参数传递的右值被视为函数内的左值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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