1. If a variable of the basic type is returned, for example:
Int;
A = 5;
Return;
Then a copy of A, that is, 5 is returned, and a is destroyed. Although a is destroyed, its copy 5 is returned successfully, so there is no problem in doing so.
2. But for the pointer obtained by non-Dynamic Allocation (New/malloc), if we do something like 1, there will be a problem, for example, inside a function:
Int A [] = {1, 2 };
Return;
Then, a copy of pointer A is returned. Assume that the address value of A is 0x002345fc. Then, the 0x2345fc can be returned successfully. After the return statement is executed, A is destroyed, that is, the memory indicated by 0x002345fc is recycled. If the address 0x002345fc is used outside the function at this time, the result is definitely incorrect. This is why the local pointer cannot be returned. The reference of the returned local variable is similar to this.
Why can't I return a reference to a local variable?
For example
Const string & mainp (const string & S)
{
String ret = s;
Return ret
}
The reference transfer is the transfer address, and the return address is the return address. If you give the address to someone else, the content on the address will be destroyed after the function call ends, so the content you direct to may not exist.
3. Another case of returning pointer (dynamically allocated), such as inside the function:
Int A = new int (5 );
Return;
This is acceptable. After return a is executed, A is not destroyed (delete is required to destroy a). Therefore, the returned a is valid.
4. If it is not a basic data type, for example:
Class
{
Public:
Otherclass *...
};
If a function contains a local variable of Class A, for example:
A;
Return;
At this time, a copy of a will also be returned. If a does not write a deep copy constructor, it will call the default copy constructor (Shortest copy). This will fail;
If a provides a deep copy constructor, this is fine.
Situations of function return values