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

前端 未结 2 582
面向向阳花
面向向阳花 2021-01-19 04:25

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 = m         


        
2条回答
  •  走了就别回头了
    2021-01-19 05:12

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

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

    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(temp).

    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.

提交回复
热议问题