Difference between const reference and normal para

2020-01-24 19:04发布

void DoWork(int n);
void DoWork(const int &n);

What's the difference?

7条回答
倾城 Initia
2楼-- · 2020-01-24 19:56

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.

查看更多
登录 后发表回答