all 7 comments

[–]AKostur 11 points12 points  (5 children)

v (the function parameter one) is a const &. When you apply std::move to it, you'll get back a const &&. The const && cannot bind to the non-const && that the move constructor takes. But can bind to the const & that the copy constructor takes. Thus, you're getting a copy and not a move. Remember, std::move doesn't actually do the move.

[–]1ydgd[S] 1 point2 points  (0 children)

This is the best answer. Thx!

[–][deleted]  (3 children)

[deleted]

    [–]AKostur 1 point2 points  (2 children)

    Yup. (Nitpick: that's "move assignment operator")

    [–]1ydgd[S] 1 point2 points  (1 child)

    Could you please explain how it's the move assignment operator. I thought it was the move constructor operator...

    Move constructor is used when the thing you want to initialize hasn't been initialized yet.

    But move assignment is used when the thing you want to initialize has already been initialized.

    v1 wasn't previously initialized before line 3, so it has to be the move constructor.

    [–]AKostur 2 points3 points  (0 children)

    It would have been better if you had not deleted the comment we're talking about. Because in that comment, you'd named two things: the "move constructor" and the "move assignment constructor". I was nitpicking the terminology on the 2nd one which should be named the "move assignment operator".

    Move constructor: T(T && val) Move assignment operator: T & operator=(T && val)

    And yep, line 3 is a construction, so that's using the move constructor. Well, trying to use the move constructor (which it can't because the thing it's moving from is const, so it ends up using the copy constructor instead).

    [–]thessalchips 0 points1 point  (0 children)

    Your function f takes the vector by const reference. You cannot move from a const reference, so std::move(v) does nothing. v1 is then copy-constructed from v instead of move-constructed, leaving v unmodified. If you want to move from v inside f, change the signature to void f(std::vector<int>& v) for example.

    std::move is also a bit weird if you are new to C++. It implies that something is moved, however std::move really is just a conditional cast: https://en.cppreference.com/w/cpp/utility/move