Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - The difference between return reference and return value in C++
The difference between return reference and return value in C++
The usual return mechanism copies the return value to a temporary storage area, and then the calling program will access the area.

If the reference is returned, the caller will directly access the return value.

Usually the reference will point to the reference passed to the function, so calling the function is actually directly accessing one of its own variables.

take for example

const? int & amp? Fun? (int & amp? First,? const? int & amp? b)

{

Answer? =? Answer? +? b;

Return? a;

}

int? x? =? 1,? y? =? 2,? z;

z? =? Fun (x,? y);

//equivalent to? Fun (x,? y); ? z? =? x;

And returning a reference cannot return a temporary variable inside a function. Because the variable is destroyed at the end of the function. The return value will be meaningless. such as

const? int & amp? Fun? (int & amp? First,? const? int & amp? b)

{

int? c? =? Answer? +? b;

Return? c;

}//The program will crash. Because the variable c is destroyed with the end of the program. Then the object with the same name returned in C is meaningless.