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
foobar
returns temporary object,xtemp1
;foo
copiesxtemp1
temporary object of own,xtemp2
, , destroyesxtemp1
;foo
performs calculations onxtemp2
.
on other side, if overload foo
as
void foo(x& x); void foo(x&& x);
then picture different and, in particular,
foobar
returns temporaryxtemp1
;foo
not create new temporary, acts directly onxtemp1
through 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
foo
executes. - 2as
foo
returns, it's parameter destructed. - 2when
foo
returns, 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
foo
executes. - as
foo
returns, it's reference parameter destructed (not value references). - 2when
foo
returns, 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