What does '&' do in a C++ declaration?

前端 未结 7 1357
后悔当初
后悔当初 2020-11-28 03:40

I am a C guy and I\'m trying to understand some C++ code. I have the following function declaration:

int foo(const string &myname) {
  cout << \"ca         


        
7条回答
  •  一生所求
    2020-11-28 04:28

    In this context & is causing the function to take stringname by reference. The difference between references and pointers is:

    • When you take a reference to a variable, that reference is the variable you referenced. You don't need to dereference it or anything, working with the reference is sematically equal to working with the referenced variable itself.
    • NULL is not a valid value to a reference and will result in a compiler error. So generally, if you want to use an output parameter (or a pointer/reference in general) in a C++ function, and passing a null value to that parameter should be allowed, then use a pointer (or smart pointer, preferably). If passing a null value makes no sense for that function, use a reference.
    • You cannot 're-seat' a reference. While the value of a pointer can be changed to point at something else, a reference has no similar functionality. Once you take a variable by reference, you are effectively dealing with that variable directly. Just like you can't change the value of a by writing b = 4;. A reference's value is the value of whatever it referenced.

提交回复
热议问题