DaE-Asew
DaE-Asew

Reputation: 137

When is a move operation performed on a function argument c++

Taking as example

void f(B b, A&& a) {...}
B g(B b, A a) {...}

int main() {
    B b;
    A a;
    f(g(b, a), std::move(a));
}

I presume this would be valid code seeing as an std::move() is merely a static_cast and from what I gather all function parameters are evaluated first (with no order guarantee) before copied / moved (which I assume is part of the function call not parameter evaluation) to the function's context.

Upvotes: 9

Views: 287

Answers (1)

BiagioF
BiagioF

Reputation: 9705

This code is valid.

As you have said, std::move is just a static_cast to rvalue (&&).

The expression:

f(g(b, a), std::move(a));

does not lead to an undefined behavior even if the arguments evaluation order is not guaranteed.

Indeed, the evaluation of the second argument std::move(a) does not affect the evaluation of the first one.

The "move operation" (here intended as the operation of "stealing" the resources held by the argument) is something can happen in the body of f (when all arguments are already evaluated).

Upvotes: 5

Related Questions