Pointer vs. Reference

后端 未结 12 1609
闹比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:37

    Pointers:

    • Can be assigned nullptr (or NULL).
    • At the call site, you must use & if your type is not a pointer itself, making explicitly you are modifying your object.
    • Pointers can be rebound.

    References:

    • Cannot be null.
    • Once bound, cannot change.
    • Callers don't need to explicitly use &. This is considered sometimes bad because you must go to the implementation of the function to see if your parameter is modified.

提交回复
热议问题