Use of the & operator in C++ function signatures

后端 未结 9 967
刺人心
刺人心 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:20

    In the case of:

    int* ptr=#
    

    you are declaring a variable named ptr with a type of an int * (int pointer), and setting its value to the "address of the variable num" (&num). The "addressof" operator (&) returns a pointer.

    In the case of:

    void DoSomething(string& str)
    

    you are declaring the first parameter of the DoSomething() method to be of type "reference to string". Effectively, this is the C++ way of defining "pass-by-reference".

    Note that while the & operator operates similarly in these cases, it's not acting in the same way. Specifically, when used as an operator, you're telling the compiler to take the address of the variable specified; when used in a method signature, you're telling the compiler that the argument is a reference. And note as well, that the "argument as a reference" bit is different from having an argument that is a pointer; the reference argument (&) gets dereferenced automatically, and there's never any exposure to the method as to where the underlying data is stored; with a pointer argument, you're still passing by reference, but you're exposing to the method where the variable is stored, and potentially exposing problems if the method fails to do a dereference (which happens more often than you might think).

提交回复
热议问题