When is a move operation performed on a function argument c++
Asked Answered
M

1

9

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.

Muslin answered 21/7, 2019 at 10:27 Comment(2)
This has nothing to with operator-precedence.Antitoxic
@Antitoxic Unfortunately the operator-precedence tag on SO is really messed up. It has a bad definition and is aliased to evaluation-order, which is what's really relevant here.Prolongate
G
5

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

Glorification answered 21/7, 2019 at 11:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.