简体   繁体   中英

Will the c++ compiler optimize away unused return value by `reference`?

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.

If the function isn't inlined, then yes the return value has to be stored somewhere, probably a CPU register. This probably just requires a single register copy. I would be surprised if the overhead was more than a single CPU cycle in most cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM