c++会吗?编译器通过“引用”优化掉未使用的返回值?
在有人跳出来说优化前分析!
之前,这只是一个好奇心问题,源于这个原始问题。
如果我通过引用返回同一个对象,如果不使用它会得到优化吗?例如,我有一个具有各种数学函数的 Vector
(假设我没有使用运算符重载)。两种编写方式:
inline void Vector::Add(const Vector& in) // Adds incoming vector to this vector
或者
inline Vector& Vector::Add(const Vector& in) // Adds incoming vector to this vector and returns a reference to this vector
现在,如果在不使用返回值的情况下使用Add()
,编译器是否会简单地完全丢弃返回值,并且该函数会变得好像没有返回值一样?如果它不是内联
怎么办?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
作为参数或返回语句的引用通常以类似于指针的方式实现,并且成本最小(在大多数情况下可以忽略不计)。根据调用约定,它可以是寄存器中的单个存储。
至于返回是否可以被优化掉,除非编译器内联代码,否则不能。当编译器处理函数时,它不知道调用代码是否会使用 return 语句,而这又意味着它必须始终返回某些内容。
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.
如果函数不是内联的,那么返回值必须存储在某个地方,可能是 CPU 寄存器。这可能只需要一个寄存器副本。如果在大多数情况下开销超过单个 CPU 周期,我会感到惊讶。
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.