VS2015和GCC 5.4.0中的Constexpr阶乘编译结果 [英] Constexpr Factorial Compilation Results in VS2015 and GCC 5.4.0

查看:77
本文介绍了VS2015和GCC 5.4.0中的Constexpr阶乘编译结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道以下情况是否会像我一样使任何人感到惊讶?Alex Allain的文章此处使用constexpr时显示以下阶乘示例:

  constexpr阶乘(int n){返回n>0?n * factorial(n-1):1;} 

并声明:

现在您可以使用阶乘(2),并且在编译器看到它时,它可以优化调用并完全在编译时进行计算时间.

我在VS2015中以发布模式对(/Ox)进行了全面优化,并在调试器中逐步查看了程序集的代码,并发现在编译时没有进行因式计算 ./p>

使用带有--std = C ++ 14的GCC v5.4.0,我必须在编译时执行计算之前使用/O2或/O3.令我惊讶的是,仅使用/O进行计算就不会在编译时发生.

主要的主要问题是:为什么VS2015在编译时不执行此计算?

解决方案

这取决于函数调用的上下文.

例如,显然在编译时无法计算以下内容:

  int x;std :: cin>>X;std :: cout<<阶乘(x); 

另一方面,此上下文在编译时会要求答案:

  Foo类{int x [factorial(4)];}; 

如果

constexpr 函数是从 constexpr 上下文中调用的,则只能保证在编译时对其进行评估.否则,由编译器决定是否在编译时进行评估(假设可以再次进行优化,这取决于上下文).

Wondering if the following surprises anyone, as it did me? Alex Allain's article here on using constexpr shows the following factorial example:

constexpr factorial (int n)
{
    return n > 0 ? n * factorial( n - 1 ) : 1;
}

And states:

Now you can use factorial(2) and when the compiler sees it, it can optimize away the call and make the calculation entirely at compile time.

I tried this in VS2015 in Release mode with full optimizations on (/Ox) and stepped through the code in the debugger viewing the assembly and saw that the factorial calculation was not done at compilation.

Using GCC v5.4.0 with --std=C++14, I must use /O2 or /O3 before the calculation is performed at compile time. I was surprised thought that using just /O the calculation did not occur at compilation time.

Main main question is: Why is VS2015 not performing this calculation at compilation time?

解决方案

It depends on the context of the function call.

For example, the following obviously could never be calculated at compile time:

int x;
std::cin >> x;
std::cout << factorial(x);

On the other hand, this context would require the answer at compile time:

class Foo {
    int x[factorial(4)];
};

constexpr functions are only guaranteed to be evaluated at compile time if they are called from a constexpr context; otherwise it is up to the compiler to choose whether or not to eval at compile time (assuming such an optimization is possible, again, depending on the context).

这篇关于VS2015和GCC 5.4.0中的Constexpr阶乘编译结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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