c++ - Rvalue references under the hood -
consider foo function
void foo(x x); with x matrix cass, , function
x foobar(); suppose run
foo(foobar()); what happens temporary objects in case step step? understanding that
foobarreturns temporary object,xtemp1;foocopiesxtemp1temporary object of own,xtemp2, , destroyesxtemp1;fooperforms calculations onxtemp2.
on other side, if overload foo as
void foo(x& x); void foo(x&& x); then picture different and, in particular,
foobarreturns temporaryxtemp1;foonot create new temporary, acts directly onxtemp1through reference.
is picture correct or, if not, point out , fix mistakes? thank much.
foo(foobar()); foobar's return value value, it's temporary value.- 1this function move/copy return value local storage temporary.
- 1this function move/copy value in local storage parameter call
foo. - the call
fooexecutes. - 2as
fooreturns, it's parameter destructed. - 2when
fooreturns, value in local storage destructed. foobar's return value destructed.
1 these moves/copies may elided compiler. means these copy/moves don't have happen (and compiler worth using elide them).
2 if moves/copies above elided, destruction of respective variables naturally unnecessary. since don't exist.
on other side, if overload foo as
foobar's return value value, it's temporary value.- 1this function move/copy return value local storage temporary.
- overload resolution selects
foo(x &&)call. - an rvalue-reference parameter variable created , initialized local storage value.
- the call
fooexecutes. - as
fooreturns, it's reference parameter destructed (not value references). - 2when
fooreturns, value in local storage destructed. foobar's return value destructed.
note key differences here. step 4 , 6 cannot elided. therefore, if x small type int, function have no choice create worthless reference integer. references internally implemented pointers, it's not possible compiler optimize away register. local storage must therefore on stack rather register.
so guaranteed of fewer move/copies. again, decent compiler elide them. question is, x large fit register?
Comments
Post a Comment