If we write the following function:
auto foo() {
Foo foo { /* ... */ };
do_stuff(foo);
return foo;
}
then NRVO should kick in, so that foo
does not get copied on return.
Now suppose I want to return two different values:
auto foo() {
Foo foo { /* ... */ };
Bar bar { /* ... */ };
do_stuff(foo, bar);
return std::make_tuple(foo, bar);
}
This naive implementation will likely trigger the construction of two copies of each Foo
and Bar
(GodBolt).
How should I best modify my code to avoid this copying, without messing up my return type?
This:
will return an
std::tuple<Foo,Bar>
(GodBolt); and will replace the copy construction by move construction (GodBolt).