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

  1. foobar returns temporary object, xtemp1;
  2. foo copies xtemp1 temporary object of own, xtemp2, , destroyes xtemp1;
  3. foo performs calculations on xtemp2.

on other side, if overload foo as

void foo(x& x); void foo(x&& x); 

then picture different and, in particular,

  1. foobar returns temporary xtemp1;
  2. foo not create new temporary, acts directly on xtemp1 through reference.

is picture correct or, if not, point out , fix mistakes? thank much.

foo(foobar()); 
  1. foobar's return value value, it's temporary value.
  2. 1this function move/copy return value local storage temporary.
  3. 1this function move/copy value in local storage parameter call foo.
  4. the call foo executes.
  5. 2as foo returns, it's parameter destructed.
  6. 2when foo returns, value in local storage destructed.
  7. 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

  1. foobar's return value value, it's temporary value.
  2. 1this function move/copy return value local storage temporary.
  3. overload resolution selects foo(x &&) call.
  4. an rvalue-reference parameter variable created , initialized local storage value.
  5. the call foo executes.
  6. as foo returns, it's reference parameter destructed (not value references).
  7. 2when foo returns, value in local storage destructed.
  8. 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

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -