This article is one of <Effective C++> reading notes.
Part 4: Designs and Declarations
Item 21: Don’t try to return a reference when you must return an object.
Things to remember
- Never return a pointer or reference to a local stack object, a reference to a heap-allocated object, or a pointer or reference to a local static object if there is a chance that more than one such object will be needed.
Key words
Stack and Heap(Isn’t std::stack or heap(data structure) “heap(data structure)”)):
- A function can create a new object in only two ways: on the stack or on the heap.
- Value types are created on the stack, and reference types are created on the heap.
- About stack, system will allocate memory to the instance of object automatically, and to the heap, you must allocate memory to the instance of object with new or malloc manually.
- When function ends, system will automatically free the memory area of the stack, but to the heap, you must free the memory area manually with free or delete, else it will result in the memory leak.
Code analysis
Bad code 1:
|
|
A more serious problem is that this function returns a reference to result, but result is a local object, and local objects are destroyed when the function exits. This version of operator*, then, doesn’t return a reference to a Rational — it returns a reference to a former and empty Rational.
Bad code 2:
|
|
Will, who will apply delete to the object conjured up by your use of new?
Bad code 3:
|
|
All designs employing the use of static objects, this one immediately raises our thread-safety hackles.
The expression if (operator==(operator(a, b), operator(c, d))) will always evaluate to true, regardless of the value of a, b, c, and d!
In any case, should avoid the use of global variables and static variables within a function.
Code
|
|