Should I now pass by value?

To say this (sorry for the sound) Chandler Carrut suggests not passing a link, even a constant link, in the vast majority of cases due to the way in which it limits the focus for optimization.

He claims that in most cases the copy is negligible, that I am happy to believe that most data structures / classes, etc. have a very small part allocated on the stack, especially compared to the background content, which the smoothing pointer should take and all the unpleasant things that could be done with the reference type.

Let's say that we have a large object on the stack - say ~ 4kB and a function that does something for an instance of this object (suppose it's an independent function).

Classically, I would write:

void DoSomething(ExpensiveType* inOut);
ExpensiveType data;
...
DoSomething(&data);

He offers:

ExpensiveType DoSomething(ExpensiveType in);
ExpensiveType data;
...
data = DoSomething(data);

In accordance with what I got from the conversation, the second will be better optimized. Is there a limit to how big I'm doing something like this, or is it a focal copy that simply prefers values ​​in almost all cases?

EDIT: To clarify, I'm interested in the whole system, since I feel that this will be a major change in the way I write code, I had the use of refs over the values ​​drilled into me for anything larger than the integral types in for a long time.

EDIT2: , . , , - -. , , , , .

+4
2

. , " ", . Edit: , , http://ericniebler.com/2013/10/13/out-parameters-vs-move-semantics/.

. , ( 4x-5x , ), :

  • , , . . ( , , .)
  • " " . in-out . , , , .
  • , , , , refs/. , " , , , , , ". .

, (, , , ) , . , , , . ( ints, 4k.)

, , , . , out . , .

:

. , ! , . ; - .

, . , , , . .

+2

, - . , . :

ExpensiveType DoSomething(ExpensiveType in) 
{
    cout << in.member;
}

, const.

:

ExpensiveType DoSomething(ExpensiveType in) 
{
    in.member = 5;
    do_something_else(in);
}

, , :

ExpensiveType DoSomething(ExpensiveType const &inr) 
{
    ExpensiveType in = inr;
    in.member = 5;
    do_something_else(in);
}

rvalue (, DoSomething( ExpensiveType(6) ); , , , move-construct in. (I , ).

NB. pass-by-reference. ++ .

0

Source: https://habr.com/ru/post/1609484/


All Articles