Terms
21
: When an object must be returned, do not think about returning it
Reference
When we understand the overhead of value transfer in Clause 20, we always avoid using less data transfer. However, we should be very careful when returning objects, because you may:
Deliver references or pointers to objects that do not actually exist. This is not a good thing.
Whenever you see a reference declarative statement, you should immediately ask yourself, what is its other name?
There are two ways for functions to create new objects: stack space and heap space.
STACK: local variables in the function. Local variables have no meaning after the function returns. If you still "Never forget" them, they will be disastrous.
Consequence.Therefore, it is not feasible to pass the reference on the stack.
STACK: Construct an object on the stack and return the object. It seems feasible, but it also hides the risk of resource leakage. Who should delete this object? Don't take this
Resources are managed by users.Therefore, it is not feasible to pass the reference to the stack.
There may be another idea: "Let the returned reference point to a static object defined in the function ". Out of our doubts about multithreading Security
And when the two functions in the thread process a single object, it may lead to unmeasurable behavior.Therefore, static objects are not feasible.
The correct syntax for a function that "must return new objects" is: let that function return a new object.
The compiler implementer implements optimization to improve the efficiency of the output code without changing its observed behavior. So we still honestly return a pair
Like.
Remember:
- Never return pointer or reference pointing to a local stack object, or return reference pointing to a heap-allocated object, or return pointer or reference pointing to a local static object, which may require multiple such objects at the same time.