c++movemove-semantics

Use after move in function call


When exactly does an object cast with std::moved get moved? For instance, does the following code constitute use after move?

f(std::move(a), a.Something())

Where f = f(A a, int x) and a is an instance of some class.

I understand that std::move(a) may be evaluated before or after a.Something(), but (since std::move is just a cast) when does the actual move occur?


Solution

  • This line:

    f(std::move(a), a.Something());
    

    Can indeed constitute a use after move.

    If your f is:

    f(A a, int x) { ... }
    

    Then the first argument will have to be either copied or moved into the parameter A a before invoking f. This means that the actual move can also take place before a.Something() is evaluated, causing a use after move.

    It's worth nothing that if your f was e.g.:

    f(A && a, int x) { ... }
    

    Then you would be safe, because std::move itself is just a cast to rvalue ref which is what is expected for A && a, and therefore no move would actually take place at the stage of evaluating the arguments for f.