Temporary Variables: Procrastination is the Thief of Time - To return or not to return an object
(Page 4 of 6 )
The example code defines a function that returns an Enemy object. Let’s take a closer look at the function declaration:
Enemy FindClosest(list<Enemy> enemies, Player player);
An example use of this function could be:
Enemy activeEnemy = FindClosest(enemyList, player);
It clearly returns an object by value, which means that a temporary object with the result of the function must be created in order for the result to be assigned to the left side of the expression that made the call.
A function might return:
- Nothing (the function returns void).
- A primitive value (int, float, bool etc).
- An object (e.g. Enemy, Vector3).
- A reference.
- A pointer.
Returning a reference or pointer to an object is much more efficient than returning the object by value, since the only data that has to be copied is the address of that object (which can comfortably be stored in a register on the CPU and doesn’t have to be transferred via memory).
A temporary object can be used by the compiler to represent a return value, and it must be constructed before it can have the result data copied into it. This temporary object is then passed to the assignment operator of the object that finally copies that result data (activeEnemy in this example case) from the temporary object into the destination object. Finally, the destructor of the temporary object can be called to clean it up.
This can be become quite a lengthy process, especially when the returned object is large in size and contains fragmented data on the memory heap. When an object contains pointers to chunks of memory on the heap (like a linked list), its copy constructor/assignment operator has to perform a deep copy to make sure that a proper copy is made.
Just as a sidenote, with a shallow copy the pointers are copied literally from one object into the other (aka a bitwise copy), whereas a deep copy allocates new memory and copies the data pointed at.
Returning a linked list by value can become a regular nightmare for a CPU, because it might have to fetch data from different portions of the regular memory pool, flushing the cache over and over again until it runs out of breath. Then it goes through the same process again when it copies the data to the object on the left hand of the assignment expression! Constructing and destructing each element of the linked list can take some time as well; after all, each element of the linked list could be a linked list in itself.
Next: Visualizing the unseen object >>
More C++ Articles
More By J. Nakamura