Before someone jumps and says Profile before optimize!
, this is simply a curiosity question and stems from this original question.
If I am returning by reference the same object, would that get optimized away if not used? For example, I have a Vector<>
that has various mathematical functions (assume I am not using operator overloading). Two ways of writing it:
inline void Vector::Add(const Vector& in) // Adds incoming vector to this vector
OR
inline Vector& Vector::Add(const Vector& in) // Adds incoming vector to this vector and returns a reference to this vector
Now if Add()
is used without utilizing the return value, will the compiler simply throw away the return altogether and the function becomes as if it has no return value to begin with? And what if it is NOT inlined
?
References as arguments or return statements are usually implemented in a manner similar to pointers and the cost is minimal (negligible in most case). Depending on the calling convention it can be a single store in a register.
As to whether the return can be optimized away, unless the compiler is inlining the code no, it cannot. When the compiler processes the function, it does not know whether calling code will use or not the return statement, and that in turn means that it must always return something.