What are the benefits to passing integral types by const ref

前端 未结 12 1824
情话喂你
情话喂你 2021-02-05 22:18

The question: Is there benefit to passing an integral type by const reference as opposed to simply by value.

ie.

void foo(const int& n); // case #1
<         


        
12条回答
  •  悲&欢浪女
    2021-02-05 22:45

    Don't do this. int is the same size as pointer/reference on common 32-bit plattforms, and smaller on 64-bit, thus you could get yourself a performance disadvantage instead of a benefit. I mean, all function arguments are pushed onto stack in order so that a function can read them, and it will either be your int, or its address in the case of reference. Another disadvantage is that the callee will either access your n through an indirection (dereferencing an address), or it will make copy on its stack as an optimization.

    If you make some changes to an int passed by value, it might be written either back onto the place on the stack where it was passed, or onto a new stack position. The second case naturally isn't advantagous, but shouldn't happen. By consting you bar yourself from making such a change, but this would work the same with const int.

    In the proper inline case it doesn't matter, naturally, but keep in mind that not everything where you write inline, will be.

提交回复
热议问题