Use of the & operator in C++ function signatures

后端 未结 9 950
刺人心
刺人心 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.

    0 讨论(0)
  • 2020-11-29 01:30

    You're inexplicitly copy-constructing copy from str. Yes, str is a reference, but that doesn't mean you can't construct another object from it. In c++, the & operator means one of 3 things -

    1. When you're defining a normal reference variable, you create an alias for an object.
    2. When you use it in a function paramater, it is passed by reference - you are also making an alias of an object, as apposed to a copy. You don't notice any difference in this case, because it basically is the object you passed to it. It does make a difference when the objects you pass contain pointers etc.
    3. The last (and mostly irrelevent to your case) meaning of & is the bitwise AND.

    Another way to think about a reference (albeit slightly incorrect) is syntactic sugar for a dereferenced pointer.

    0 讨论(0)
  • 2020-11-29 01:32
    int* ptr=#
    

    1st case: Since ptr is a memory and it stores the address of a variable. The & operator returns the address of num in memory.

    void DoSomething(string& str)
    

    2nd case: The ampersand operator is used to show that the variable is being passed by reference and can be changed by the function.

    So Basically the & operator has 2 functions depending on the context.

    0 讨论(0)
提交回复
热议问题