Difference between const reference and normal parameter

前端 未结 7 1994
我寻月下人不归
我寻月下人不归 2020-11-28 01:09
void DoWork(int n);
void DoWork(const int &n);

What\'s the difference?

7条回答
  •  佛祖请我去吃肉
    2020-11-28 01:35

    The difference is more prominent when you are passing a big struct/class.

    struct MyData {
        int a,b,c,d,e,f,g,h;
        long array[1234];
    };
    void DoWork(MyData md);
    void DoWork(const MyData& md);
    

    when you use use 'normal' parameter, you pass the parameter by value and hence creating a copy of the parameter you pass. if you are using const reference, you pass it by reference and the original data is not copied.

    in both cases, the original data cannot be modified from inside the function.

    EDIT:
    In certain cases, the original data might be able to get modified as pointed out by Charles Bailey in his answer.

提交回复
热议问题