Passing integers as constant references versus copying

前端 未结 5 1533
无人及你
无人及你 2020-11-28 23:57

This might be a stupid question, but I notice that in a good number of APIs, a lot of method signatures that take integer parameters that aren\'t intended to be modified loo

5条回答
  •  既然无缘
    2020-11-29 00:14

    To me, it looks like both of these would function exactly the same.

    It depends on exactly what the reference is to. Here is an admittedly made up example that would change based on whether you pass a reference or a value:

    static int global_value = 0;
    
    int doit(int x)
    {
        ++global_value;
        return x + 1;
    }
    
    int main()
    {
        return doit(global_value);
    }
    

    This code will behave differently depending on whether you have int doit(int) or int doit(const int &)

提交回复
热议问题