Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 414
DaE-Asew Avatar asked Jul 21 '19 10:07

DaE-Asew


People also ask

When should we use std :: move?

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.

How arguments are passed to functions in C?

Arguments in C and C++ language are copied to the program stack at run time, where they are read by the function. These arguments can either be values in their own right, or they can be pointers to areas of memory that contain the data being passed. Passing a pointer is also known as passing a value by reference.

Can we use a function as a parameter of another function in C?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.


1 Answers

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

like image 197
BiagioF Avatar answered Oct 11 '22 06:10

BiagioF