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

前端 未结 7 1214
后悔当初
后悔当初 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:47

    Your function declares a constant reference to a string:

    int foo(const string &myname) {
      cout << "called foo for: " << myname << endl;
      return 0;
    }
    

    A reference has some special properties, which make it a safer alternative to pointers in many ways:

    • it can never be NULL
    • it must always be initialised
    • it cannot be changed to refer to a different variable once set
    • it can be used in exactly the same way as the variable to which it refers (which means you do not need to deference it like a pointer)

    How does the function signature differ from the equivalent C:

    int foo(const char *myname)
    

    There are several differences, since the first refers directly to an object, while const char* must be dereferenced to point to the data.

    Is there a difference between using string *myname vs string &myname?

    The main difference when dealing with parameters is that you do not need to dereference &myname. A simpler example is:

    int add_ptr(int *x, int* y)
    {
        return *x + *y;
    }
    int add_ref(int &x, int &y)
    {
        return x + y;
    }
    

    which do exactly the same thing. The only difference in this case is that you do not need to dereference x and y as they refer directly to the variables passed in.

    const string &GetMethodName() { ... }
    

    What is the & doing here? Is there some website that explains how & is used differently in C vs C++?

    This returns a constant reference to a string. So the caller gets to access the returned variable directly, but only in a read-only sense. This is sometimes used to return string data members without allocating extra memory.

    There are some subtleties with references - have a look at the C++ FAQ on References for some more details.

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