为什么这需要一个明确的std :: move? [英] Why does this need an explicit std::move?

查看:100
本文介绍了为什么这需要一个明确的std :: move?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 Foo 类,其中包含从构建的 std :: vector std :: unique_ptr 另一个类的对象 Bar

Let's say I got a Foo class containing an std::vector constructed from std::unique_ptr objects of another class, Bar.

typedef std::unique_ptr<Bar> UniqueBar;

class Foo {
    std::vector<UniqueBar> bars;
public:
    void AddBar(UniqueBar&& bar);
};

void Foo::AddBar(UniqueBar&& bar) {
    bars.push_back(bar);
}

这会导致编译错误(在g ++ 4.8.1中)复制构造函数 std :: unique_ptr 被删除,这是合理的。这里的问题是,因为bar参数已经是一个右值引用,为什么调用 std :: unique_ptr 的复制构造函数而不是其move构造函数?

This one results in a compilation error (in g++ 4.8.1) saying that the the copy constructor of std::unique_ptr is deleted, which is reasonable. The question here is, since the bar argument is already an rvalue reference, why does the copy constructor of std::unique_ptr is called instead of its move constructor?

如果我在 Foo :: AddBar 中显式调用 std :: move 然后编译问题消失,但我不明白为什么这是需要的。我认为这是多余的。

If I explicitly call std::move in Foo::AddBar then the compilation issue goes away but I don't get why this is needed. I think it's quite redundant.

那么,我错过了什么?

So, what am I missing?

推荐答案

基本上,每个具有名称的对象都是一个左值。当使用右值引用将对象传递给函数时,函数实际上会看到一个左值:它被命名。

Basically, every object which has a name is an lvalue. When you pass an object to a function using an rvalue reference the function actually sees an lvalue: it is named. What the rvalue reference does, however, indicate is that it came from an object which is ready to be transferred.

换句话说,右值引用是不对称的:

Put differently, rvalue references are assymmetrical:


  • ,它们只能接收rvalue,即临时对象,要离开的对象或看起来好像是rvalues的对象(例如,结果 std :: move(o)

  • 然而,右值引用本身看起来像一个左值

这篇关于为什么这需要一个明确的std :: move?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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