简体   繁体   中英

C++ Basic concept regarding reference operator return type

I need to clear a basic concept. This code works fine. Can somebody explain me that if the function calDouble already returning the address (reference) of int why I need to use & operator further in main int *j = &calDouble(i); to get the address (reference) of int? Thanks.

int& calDouble(int x)
{
    x = x*2;
    return x;

}

int main(int argc, char *argv[])
{
    int i = 99;
    int *j = &calDouble(i);

    system("PAUSE");
    return EXIT_SUCCESS;
}

int& calDouble(int x) doesn't return an address, but a reference to an int .

You need to take the address of the reference to be able to assign it to a pointer.

Note however that your code invokes undefined behavior . Because you pass the parameter by value, a copy of it is created inside the function. So you return a local variable by reference, which is not legal.

I think your confusion comes from & . This can be used in two ways:

  • applied to a variable &x , it takes its address
  • when in a declaration int& x , it defines a reference

A reference is just an alias, a different name for a variable.

int x = 0;
int& y = x;

Now, x and y refer to the same variable.

int* z = &x;

takes the address of x .

int& is a reference type. It is not the address.

To see what &calDouble(i) does, consider if we had broken it into two statements:

int& x = calDouble(i);
... = &x;

The calDouble() function returns a reference type, and the prepended & then takes the address-of whatever was returned. So the type is now int* , which is why that line compiles.

However, your program exhibits undefined behavior! The x in calDouble() goes away once the function ends. The value that was originally there may still be in memory , which is why your program "works". But this is not reliable in production code, and one day your perfectly working test program may blow-up the moment it's deployed.

It's generally a bad idea to return a reference to a local variable for this vary reason. (You'll see class methods return references to member data, which is fine as long as the object is still in scope since those variables will still exist.) Just return a regular int and get on with life. An optimizing compiler can do some return value optimization if you're really worried about performance when returning large objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM