为什么三元运算符阻止返回值优化? [英] Why does the ternary operator prevent Return-Value Optimization?

查看:72
本文介绍了为什么三元运算符阻止返回值优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么三元运算符会阻止MSVC中的返回值优化(RVO)?考虑以下完整的示例程序:

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\n"; }
};

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:\n";
    Example obj1 = FunctionUsingIf(0);
    std::cout << "using ternary operator:\n";
    Example obj2 = FunctionUsingTernaryOperator(0);
}

使用VC 2013进行如下编译: cl/nologo/EHsc/Za/W4/O2 stackoverflow.cpp

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

输出:

using if:
using ternary operator:
copy

因此,显然三元运算符以某种方式阻止了RVO.为什么?为什么编译器不够聪明,以至于看到使用三元运算符的函数与使用if语句的函数做了相同的事情,并相应地进行了优化?

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?

推荐答案

在查看程序输出时,在我看来,确实编译器在两种情况下都处于屏蔽状态,为什么?

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. 在函数返回时构造示例对象;
  2. 将其复制到临时文件;
  3. 将临时文件复制到主函数中定义的对象中.

因此,我希望屏幕上至少输出2个副本".确实,如果我用-fno-elide-constructor执行用g ++编译的程序,则每个函数都会得到2条复制消息.

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.

足够有趣,如果我使用clang进行相同操作,则在调用函数 FunctionUsingTernaryOperator(0); 时收到3条复制"消息,我想这是由于三元函数是由编译器实现.我猜它正在生成一个临时值来解决三元运算符,并将其复制到return语句中.

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.

这篇关于为什么三元运算符阻止返回值优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆