Use of the & operator in C++ function signatures

后端 未结 9 953
刺人心
刺人心 2020-11-29 00:36

I\'m currently reading through Accelerated C++ and I realized I don\'t really understand how & works in function signatures.

int* ptr=#
         


        
9条回答
  •  一整个雨季
    2020-11-29 01:27

    In the case of assigning variables (ie, int* ptr = &value), using the ampersand will return the address of your variable (in this case, address of value).

    In function parameters, using the ampersand means you're passing access, or reference, to the same physical area in memory of the variable (if you don't use it, a copy is sent instead). If you use an asterisk as part of the parameter, you're specifying that you're passing a variable pointer, which will achieve almost the same thing. The difference here is that with an ampersand you'll have direct access to the variable via the name, but if you pass a pointer, you'll have to deference that pointer to get and manipulate the actual value:

    void increase1(int &value) {
       value++;
    }
    
    void increase2(int *value) {
       (*value)++;
    } 
    
    void increase3(int value) {
       value++;
    }
    

    Note that increase3 does nothing to the original value you pass it because only a copy is sent:

    int main() {
       int number = 5;
       increase1(number);
       increase2(&number);
       increase3(number);
       return 0;
    }
    

    The value of number at the end of the 3 function calls is 7, not 8.

提交回复
热议问题