gpt4 book ai didi

c++ 11通过constexpr在编译时获取字符串长度

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:28:31 26 4
gpt4 key购买 nike

#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;
}

最佳答案

constexpr 函数只能在使用编译时常量参数调用时在编译时求值。虽然 p 的值可以通过静态分析确定(它在初始化和计算之间不会改变),但它不是标准定义中的常量表达式。

试试这个:

constexpr const char* p = "1234567";

此外,您可以通过将初始化变量声明为 constexpr 来保证初始化是可行的,而不会产生运行时开销:

constexpr size_t i = constLength(p);

关于c++ 11通过constexpr在编译时获取字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27498592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com