我正在阅读 Effective Modern C++ 并想尝试使用常量表达式来尝试一个非常基本的函数。我的 C++ 技能确实不是很好,但我无法弄清楚这段基本代码有什么问题:
constexpr int test( int x ) {
// works if: return x == 43337, otherwise segmentation fault
return x > 1000000 ? x+1 : test( x + 1 );
}
int main(int argc, char const *argv[])
{
constexpr auto x = 0;
cout << "Result: " << test( x );
return 0;
}
如评论中所述,如果我使用 return x == 43337,则此代码有效,但任何更大的值都会导致分段错误。
这段代码有什么问题?如果我正确理解了 const 表达式,则计算应该在编译时进行,但是在我看来,计算是在运行时进行的。更大的值似乎会导致分段错误,因为调用堆栈太深。
但是,我不确定为什么我没有收到任何编译器错误,因为计算应该在编译时进行(显然不是)。
此外,如果我的方法签名如下所示,此代码是否有效:
constexpr decltype(auto) test( int x )
答案 0 :(得分:1)
在您的代码中,您没有在需要编译时评估的上下文中调用 test
,因此编译器可以在运行时自由地评估调用,从而导致段错误。
您可以通过使用结果初始化 test
变量来强制调用 constexpr
的编译时上下文:
constexpr auto result = test( x ); // error
这如预期的那样给出了 compile time error:
error: constexpr variable 'result' must be initialized by a constant expression
constexpr auto result = test( x );
^ ~~~~~~~~~
note: constexpr evaluation exceeded maximum depth of 512 calls
...