【问题标题】:constexpr doesn't seem to workconstexpr 似乎不起作用
【发布时间】:2015-03-02 03:12:08
【问题描述】:

我正在使用 Visual Studio 2013 + CTP。

我定义了以下函数:

constexpr DWORD const_getHash(const char *str, DWORD curHash = 0) {
    return !*str ? curHash : const_getHash(str + 1, 
        (curHash >> 13 | curHash << (32 - 13)) + (*str >= 'a' ? *str - 32 : *str));
}

我是这样使用的:

DWORD hash = const_getHash("ok");

编译器不会发出任何警告,但通过查看“反汇编”,我可以知道 const_getHash() 是在运行时执行的。

怎么了?

编辑:如果我强制函数在编译时执行

constexpr DWORD hash = const_getHash("ok");

编译器说

Error   1   error C2127: 'hash': illegal initialization of 'constexpr' entity with a non-constant expression

【问题讨论】:

  • 这可能是 VS 编译器的一些限制,因为它适用于 GCC
  • @TomKnapen 该死!那时我可能会求助于 GCC。我无法在运行时计算哈希,因为我正在编写一个需要尽可能小的 shellcode。

标签: c++ c++11 constexpr


【解决方案1】:

constexpr 不会强制函数在编译时执行。它只是告诉编译器可以在编译时执行如果需要。

constexpr 函数将在编译时计算,当它的所有参数都是常量表达式并且结果也用于常量表达式时。

(引自已接受的答案here。)

【讨论】:

    猜你喜欢
    • 2014-08-26
    • 2016-11-29
    • 2016-02-01
    • 2020-09-23
    • 2010-12-05
    • 2011-06-14
    • 2015-01-10
    • 2016-02-24
    • 2011-01-18
    相关资源
    最近更新 更多