Pointer vs. Reference

后端 未结 12 1607
闹比i
闹比i 2020-11-22 11:13

What would be better practice when giving a function the original variable to work with:

unsigned long x = 4;

void func1(unsigned long& val) {
     val          


        
12条回答
  •  没有蜡笔的小新
    2020-11-22 11:36

    Pass by const reference unless there is a reason you wish to change/keep the contents you are passing in.

    This will be the most efficient method in most cases.

    Make sure you use const on each parameter you do not wish to change, as this not only protects you from doing something stupid in the function, it gives a good indication to other users what the function does to the passed in values. This includes making a pointer const when you only want to change whats pointed to...

提交回复
热议问题