C++: Why pass-by-value is generally more efficient than pass-by-reference for built-in (i.e., C-like) types

后端 未结 3 2178
一向
一向 2020-12-01 09:41

just as what indicated in the title

3条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 09:55

    For pod types like int, char, short, and float the size of the data is the same size (or smaller) than the address passed in to reference the actual data. Looking up the value at the referenced address is an unnecessary step and adds additional cost.

    For example, take the following functions foo and bar

    void foo(char& c) {...}
    void bar(char c) {...}
    

    When foo is called an address is passed by value of either 32bits or 64bits, depending on your platform. When you use c within foo you have the cost of looking up the value of data held at the passed in address.

    When calling bar a value of the size of char is passed in and there is no address lookup overhead.

提交回复
热议问题