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

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; }; 
+4
source share
2 answers

There are two potential locations in your code where you can expect the move constructor to be called (but it is not):

1) call std :: move
2) at the time of appointment.

As for 1), std :: move makes a simple actor - it does not create an object from a copy - if it were possible, the move constructor could be called by it, but since it performs a simple rvalue cast, t is called. The definition of std :: move is similar to static_cast<Event&&>(temp) .

As for 2), initialization and purpose are two completely different operations (although the "=" symbol is used in some forms of initialization). Your code performs the assignment and therefore uses the default assignment operator, which is declared to accept a reference to the lvalue constant. Since you never initialize one event object to another, you will not see that your move constructor is called. If you declared a forwarding assignment operator: Event& operator=(Event&& other) , then your current code will call it or if you wrote: Event a; Event tmp = move(a); Event a; Event tmp = move(a); your move constructor, as written, will be called.

+10
source

You are not using a 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 a redirection assignment operator that does not exist in your code, so it returns to the copy assignment operator.

+11
source

Source: https://habr.com/ru/post/1286788/


All Articles