Why does the ternary operator prevent Return-Value Optimization?

后端 未结 3 1872
暗喜
暗喜 2020-12-19 00:08

Why does the ternary operator prevent Return-Value Optimization (RVO) in MSVC? Consider the following complete example program:

#include 

st         


        
3条回答
  •  星月不相逢
    2020-12-19 00:53

    This related question contains the answer.

    The standard says when copy or move elision is allowed in a return statement: (12.8.31)

    • in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cvunqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value
    • when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

    So basically copy elision only occures in the following cases:

    1. returning a named object.
    2. returning a temporary object

    If your expression is not a named object or a temporary, you fall back to copy.

    Some Interesting behaviors:

    • return (name); does not prevent copy elision (see this question)
    • return true?name:name; should prevent copy elision but gcc 4.6 at least is wrong on this one (cf. this question)

    EDIT:

    I left my original answer above but Christian Hackl is correct in his comment, it does not answer the question.

    As far as the rules are concerned, the ternary operator in the example yields a temporary object so 12.8.31 allows the copy/move to be elided. So from the C++ language point of view. The compiler is perfectly allowed to elide the copy when returning from FunctionUsingTernaryOperator.

    Now obviously the elision is not done. I suppose the only reason is that Visual Studio Compiler team simply did not implement it yet. And because in theory they could, maybe in a future release they will.

提交回复
热议问题