I. By default, the return value of a function is passed by value.
This means that the function with control will receive copies of the expressions specified in the return statement, for example:
Matrix grow (matrix * P ){
Matrix val;
//...
Return val;
}
Grow () returns the copy of the value stored in Val to the called function, but the called function cannot be modified in any way.
2. The default behavior can be changed. A function can be declared as returning a pointer or reference.
When the function returns a reference, the call function receives the left value of Val, that is, the call function can modify Val or obtain its address. Grow () can return a reference as follows:
Matrix & grow (matrix * P ){
Matrix * res;
// Allocate a larger matrix in Dynamic Storage
// RES is a pointer to the new matrix.
// Copy * P content to * res
Return * res;
}
If the returned value is a large class object, it is much more efficient to use a reference or pointer to return a type than to return a class object by value, in some cases, the compiler automatically converts a return value to a return value by reference. This optimization is called named return value optimization ).
When a referenced function is declared,ProgramPersonnel should be aware of the following two mistakes:
1.The life cycle of a local object referenced to a local object ends with the end of the function. After the function ends, the reference is changed to an alias of undefined memory. For example:
// Problem: a reference pointing to a local object is returned.
Matrix & add (Matrix & M1, Matrix & m2)
{
Matrix result;
If (m1.iszero ())
Return m2;
If (m2.iszero ())
Return M1;
// Add the content of two matrix objects
// Oh! The returned result points to a problematic location.
Return result;
}
In this case, the return type should be declared as a non-reference type, and then copy the local variable before the lifetime of the local object.
Matrix add (...
2.If the function returns a left value, any modification to the return value will change the actual object to be returned. For example:
# Include <vector>
Int & get_val (vector <int> & VI, int IX ){
Return VI [ix];
}
Int Ai [4] = {0, 1, 2, 3 };
Vector <int> VEC (AI, AI + 4); // copy the four elements of AI to VEC
Int main (){
// Increase VEC [0] to 1
Get_val (VEC, 0) ++;
//...
}
To prevent unintentional modification to the reference return value, the return value should be declared as const:
Const Int & get_val (...