I have a function that "builds" a structure to return:
struct stuff {
int a;
double b;
Foo c;
};
stuff generate_stuff() {
Foo c = generate_foo();
//do stuff to Foo, that changes Foo:
//...
return {1, 2.0, c}; //should this be return {1, 2.0, move(c)};?
}
Should I be moving c
out of the function? I realize that frequently, (N)RVO can build the object in place, however there might be times when this ISN'T the case. When can't (N)RVO be done, and thus, when should I move an object of a function?
Put another way, this is obviously going to be RVO of the temporary that is returned. The question becomes, will NRVO (named return value optimization) happen with c
? Will c
be constructed in place (at the call site of the function, inside the temporary stuff
structure), or will c
be constructed in the function, and then copied into the structure at the call site.