Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c++ - Why does the ternary operator prevent Return-Value Optimization?

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

#include <iostream>

struct Example
{
    Example(int) {}
    Example(Example const &) { std::cout << "copy
"; }
};

Example FunctionUsingIf(int i)
{
    if (i == 1)
        return Example(1);
    else
        return Example(2);
}

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

int main()
{
    std::cout << "using if:
";
    Example obj1 = FunctionUsingIf(0);
    std::cout << "using ternary operator:
";
    Example obj2 = FunctionUsingTernaryOperator(0);
}

Compiled like this with VC 2013: cl /nologo /EHsc /Za /W4 /O2 stackoverflow.cpp

Output:

using if:
using ternary operator:
copy

So apparently the ternary operator somehow prevents RVO. Why? Why would the compiler not be clever enough to see that the function using the ternary operator does the same thing as the one using the if statement, and optimize accordingly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looking at the program output, it seems to me that, indeed, the compiler is eliding in both cases, why?

Because, if no elide was activated, the correct output would be:

  1. construct the example object at function return;
  2. copy it to a temporary;
  3. copy the temporary to the object defined in main function.

So, I would expect, at least 2 "copy" output in my screen. Indeed, If I execute your program, compiled with g++, with -fno-elide-constructor, I got 2 copy messages from each function.

Interesting enough, If I do the same with clang, I got 3 "copy" message when the function FunctionUsingTernaryOperator(0); is called and, I guess, this is due how the ternary is implemented by the compiler. I guess it is generating a temporary to solve the ternary operator and copying this temporary to the return statement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...