Function return values include values, references, and pointers. References are not available in C ++, And because references are the basis for the continuous operation of operators implemented by the Left value, neither values nor references are allowed. The following describes the features of the three return methods:
1. Return Value
Int test1 () {int A = 1; retur ;}
The return value is the simplest and most effective method. Its operation is mainly on the stack. According to the features of the Function stack, local variable A will be deleted at the end of the function. In order to return the value of, A replication is required. It doesn't matter if A is an atomic type, but if A is a large object, copying a will produce serious resource and performance consumption. Note that the function return value itself cannot be directly operated because there is no name or reference is a right value.
2. Return pointer
Int * Test2 () {int * B = new int (); * B = 2; return B ;}
The return pointer is the only method except the return value in C. It will also generate a copy based on the features of the Function stack, but this copy is only a 4 (8) byte pointer, returning large objects can reduce resource consumption. However, the cleanup of the returned pointer resource is handed over to the caller, which in some sense violates the principle of who applies for destruction. The pointer is also the right value and cannot be operated.
3. Return reference
Int & Test2 () {int * B = new int (); * B = 2; return * B ;}
References are newly added to C ++. Therefore, the returned references are not found in C ++ compared to C. Reference is the alias of a value. Like a pointer, there is no replication of the large object itself, but the replication of the alias is referenced. The reference is a left value, and the return reference can be operated directly, so that continuous value assignment can be performed. The most typical example is to copy the constructor and reload the operator and generally return the reference.
Test2 () + = 1;
However, returning a reference will bring about a problem, that is, returning the memory space of the local variable will produce an exception, that is, the local variable cannot be returned as a reference. The local pointer can be returned as a reference, but like the returned pointer, the caller needs to clear the memory himself.