#include <stdio.h>
constexpr size_t constLength(const char* str)
{
return (*str == 0) ? 0 : constLength(str + 1) + 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
const char* p = "1234567";
size_t i = constLength(p);
printf(p);
printf("%d", i);
return 0;
}
大家好我想在编译时获得一个字符串的长度,所以我在上面写了代码,但是在反汇编代码中,我发现下面的名为sub_401000的'constLength'函数将导致计算字符串长度的运行时开销。有什么问题吗?(Visual Studio 2015预览版,通过最大化速度(/ O2)优化发布)
int __cdecl sub_401010()
{
int v0; // esi@1
v0 = sub_401000("234567") + 1;
sub_401040(&unk_402130);
sub_401040("%d");
return 0;
}
int __thiscall sub_401000(void *this)
{
int result; // eax@2
if ( *(_BYTE *)this )
result = sub_401000((char *)this + 1) + 1;
else
result = 0;
return result;
}
A constexpr
函数仅当使用作为编译时常量的参数调用时才能在编译时求值。尽管p
的值可以通过静态分析确定(在初始化和评估之间不会改变),但根据标准定义,它不是常数表达式。
尝试一下:
constexpr const char* p = "1234567";
此外,您可以通过将已初始化的变量声明为constexpr
来确保无需运行时开销即可进行初始化。>
constexpr size_t i = constLength(p);
为了在编译时强制执行评估,有一些技巧。首先,您可以在枚举中使用该值。但是,这会用“垃圾”枚举污染您的命名空间。