编译时"strlen()"有效吗?

Dmi*_*riy 12 c++ string performance templates

有时需要将字符串的长度与常量进行比较.
例如:

if ( line.length() > 2 )
{
    // Do something...
}
Run Code Online (Sandbox Code Playgroud)

但我试图避免在代码中使用"魔术"常量.
通常我使用这样的代码:

if ( line.length() > strlen("[]") )
{
    // Do something...
}
Run Code Online (Sandbox Code Playgroud)

由于函数调用,它更具可读性,但效率更高.
我写了模板函数如下:

template<size_t N>
size_t _lenof(const char (&)[N])
{
    return N - 1;
}

template<size_t N>
size_t _lenof(const wchar_t (&)[N])
{
    return N - 1;
}

// Using:
if ( line.length() > _lenof("[]") )
{
    // Do something...
}
Run Code Online (Sandbox Code Playgroud)

在发布版本(VisualStudio 2008)中,它生成了非常好的代码:

cmp    dword ptr [esp+27Ch],2 
jbe    011D7FA5 
Run Code Online (Sandbox Code Playgroud)

好的是编译器在二进制输出中不包含"[]"字符串.

它是特定于编译器的优化还是常见行为?

Wil*_*ell 12

为什么不

sizeof "[]" - 1;

(减去一个尾随空.你可以做sizeof"[]" - sizeof'\ 0',但sizeof'\ 0'在C中通常是sizeof(int),而" - 1"是完全可读的.)


Rob*_*edy 5

内联函数调用的功能既是特定于编译器的优化,也是常见的行为.也就是说,许多编译器都可以这样做,但它们并不是必需的.