Temporary Variables: Procrastination is the Thief of Time
C++ is a powerful programming language to learn, in part because it gives you full control over memory management. This is a two-edged sword, however; it lets you improve the performance of your code, but it also lets you shoot yourself in the foot. Therefore, it is important to understand the C++ compiler. This article examines how and why the compiler creates temporary objects, among other topics.
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).
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.