How to pass “literal” integers by reference in C++ (Newbie)

后端 未结 5 477
温柔的废话
温柔的废话 2020-12-03 17:23

Edit: As many people have pointed out, pass-by-reference isn\'t generally appropriate as an optimisation for primitive types. This is excellent to know, so

5条回答
  •  难免孤独
    2020-12-03 17:51

    Passing by reference is actually slower for such small values. To pass by reference, it is, under-the-hood, passing a pointer (which is an int-sized value anyway). Then, there is a hidden extra pointer indirection that is not free. It is more direct to simply pass the value.

    Do this:

    void fillRect( int x, int y, int width, int height )
    {
        // do something
    }
    

    The compiler will most likely inline your function anyway, unless its big. So you wouldn't have been able to improve the performance by being "clever" in how you declared the function.

提交回复
热议问题