strlen 是否针对字符串文字进行了优化?

Jon*_*Mee 4 c++ c-strings string-length string-literals compile-time-constant

所以说我有这个:

const auto foo = "lorem ipsum"
Run Code Online (Sandbox Code Playgroud)

如果我strlen(foo)在代码中使用,11 是在运行时找到的还是在编译时注入的?

das*_*ght 5

答案取决于编译器和当前的优化级别。

使用此 C++ 代码进行快速实验

#include <cstring>
int strlen_of_const() {
    return strlen("lorem ipsum");
}
Run Code Online (Sandbox Code Playgroud)

编译器资源管理器显示,某些编译器会优化调用,而其他编译器会在运行时进行调用。例如,gcc 优化了调用:

strlen_of_const():
  mov eax, 11
  ret
Run Code Online (Sandbox Code Playgroud)

另一方面,MSVC 保留通话:

$SG3533 DB        'lorem ipsum', 00H
EXTRN   strlen:PROC
strlen_of_const PROC
        sub      rsp, 40              ; 00000028H
        lea      rcx, OFFSET FLAT:$SG3533
        call     strlen
        add      rsp, 40              ; 00000028H
        ret      0
strlen_of_const ENDP
Run Code Online (Sandbox Code Playgroud)