Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this C++0x code call the move constructor?

Tags:

c++

c++11

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);

why not?

Using std::swap calls it once.

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;
};
like image 379
Neil G Avatar asked Nov 30 '22 20:11

Neil G


1 Answers

You are not using the move constructor. I think swap is implemented something like this

Event a;
Event b;

Event temp(move(a)); // this one wants to use a move constructor
a = move(b);
b = move(temp);

You want to use the move assignment operator, which doesn't exist in your code, so it falls back to the copy assignment operator.

like image 157
Johannes Schaub - litb Avatar answered Dec 15 '22 03:12

Johannes Schaub - litb