编译器会优化掉未使用的返回值吗

编译器会优化掉未使用的返回值吗

本文介绍了c ++编译器会优化掉未使用的返回值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个函数返回一个对象,但这个返回值从不使用调用者,编译器会优化离开副本吗?

If I have a function that returns an object, but this return value is never used by the caller, will the compiler optimize away the copy? (Possibly an always/sometimes/never answer.)

小学范例:

ReturnValue MyClass::FunctionThatAltersMembersAndNeverFails()
{
    //Do stuff to members of MyClass that never fails
    return successfulResultObject;
}

void MyClass::DoWork()
{
    // Do some stuff
    FunctionThatAltersMembersAndNeverFails();
    // Do more stuff
}

在这种情况下, code> ReturnValue object被复制?它甚至构建吗? (我知道它可能取决于编译器,但让我们把这个讨论缩小到流行的现代的。)

In this case, will the ReturnValue object get copied at all? Does it even get constructed? (I know it probably depends on the compiler, but let's narrow this discussion down to the popular modern ones.)

编辑:让我们简化这一点,在一般情况下似乎是一个共识。如果 ReturnValue 是一个int,我们返回0,而不是 successResultObject

Let's simplify this a bit, since there doesn't seem to be a consensus in the general case. What if ReturnValue is an int, and we return 0 instead of successfulResultObject?

推荐答案

如果ReturnValue类有一个非平凡的复制构造函数,编译器不能消除对复制构造函数的调用 - 它被调用的语言。

If the ReturnValue class has a non-trivial copy constructor, the compiler must not eliminate the call to the copy constructor - it is mandated by the language that it is invoked.

如果复制构造函数是内联的,编译器可能能够内联调用,这反过来可能导致消除其大部分代码(也取决于是否FunctionThatAltersMembersAndNeverFails为inline)。

If the copy constructor is inline, the compiler might be able to inline the call, which in turn might cause a elimination of much of its code (also depending on whether FunctionThatAltersMembersAndNeverFails is inline).

这篇关于c ++编译器会优化掉未使用的返回值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 21:49