Why does the ternary operator prevent Return-Value Optimization?

后端 未结 3 1869
暗喜
暗喜 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 01:03

    I can see that it violates one general rule about RVO – that the return object (should) be defined at a single position.

    The snippet below satisfies the rule:

    Example e;
    e = (i == 1)? Example{1} : Example{2};
    return e;
    

    But in the original expression like below, two Example objects are defined at two different positions according to MSVC:

    return (i == 1) ? Example(1) : Example(2);
    

    While the conversion between the two snippets is trivial to humans, I can imagine that it doesn't automatically happen in the compiler without a dedicated implementation. In other words, it's a corner case which is technically RVO-able but the devs didn't realize.

提交回复
热议问题