为什么这个C ++ 0x代码调用move构造函数? [英] Why doesn't this C++0x code call the move constructor?

查看:144
本文介绍了为什么这个C ++ 0x代码调用move构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因,以下代码不会调用 Event :: Event(Event& e)

For some reason, the following code never calls Event::Event(Event&& e)

Event a;
Event b;
Event temp;
temp = move(a);
a = move(b);
b = move(temp);

为什么不?

使用 std :: swap 调用一次。

class Event {
public:
    Event(): myTime(0.0), myNode(NULL) {}
    Event(fpreal t, Node* n);
    Event(Event&& other);
    Event(Event const& other) = delete;
    ~Event();

    bool				operator<(Event const& other) const { return myTime < other.myTime; }
    bool				operator>(Event const& other) const { return myTime > other.myTime; }
    fpreal				getTime() const { return myTime; }
    void				setTime(fpreal time) { myTime = time; }
    Node*				getNode() const { return myNode; }

private:
    fpreal				myTime;
    Node*				myNode;
};


推荐答案

您的代码有两个潜在位置移动构造函数被调用(但不是):

Your code has two potential locations for where one may expect the move constructor to get called (but it doesn't):


1)调用std :: move

2)。

1) calling std::move
2) during assignment.

关于1),std :: move会执行一个简单的转换 - 它不会从副本创建一个对象移动构造函数可能会被它调用,但由于它做了一个简单的右值转换,它不会被调用。 std :: move的定义类似于 static_cast< Event&&>(temp)

Regarding 1), std::move does a simple cast - it does not create an object from a copy - if it did then the move constructor might get invoked by it, but since it does a simple rvalue cast it doesn't get invoked. The definition of std::move is similar to static_cast<Event&&>(temp).

关于2),初始化和赋值是两个完全不同的操作(即使一些形式的初始化使用'='符号)。您的代码分配,因此使用默认的赋值操作符,它被声明为接受一个const lvalue引用。因为你从来没有用另一个事件对象初始化一个事件对象,你不会看到你的移动构造函数被调用。如果你声明了一个移动赋值运算符: Event& operator =(Event&& other),那么你当前的代码将调用它,或者如果你写: Event a;事件tmp = move(a); 你的移动构造函数,如写的,将被调用。

Regarding 2), Initialization and assignment are two entirely different operations (even though some forms of initialization use the '=' symbol). Your code does assignment and therefore uses the default assignment operator which is declared to accept a const lvalue reference. Since you never initialize one event object with another, you won't see your move constructor get invoked. If you declared a move assignment operator: Event& operator=(Event&& other), then your current code would invoke it or if you wrote: Event a; Event tmp = move(a); your move constructor, as written, would get invoked.

这篇关于为什么这个C ++ 0x代码调用move构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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