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
}

在这种情况下,ReturnValue 对象会被复制吗?它甚至可以构建吗?(我知道这可能取决于编译器,但让我们将讨论范围缩小到流行的现代编译器.)

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 而不是 successfulResultObject 怎么办?

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 是否内联).

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).

相关文章