我很好奇下面这段代码:
#include <string>
int main()
{
std::string a = "ABCDEFGHIJKLMNO";
}
当使用-O3
编译时,会产生以下代码:
main: # @main
xor eax, eax
ret
(我完全明白未使用的a
没有必要,编译器可以完全从生成的代码中省略它)
然而下面的程序:
#include <string>
int main()
{
std::string a = "ABCDEFGHIJKLMNOP"; // <-- !!! One Extra P
}
产生:main: # @main
push rbx
sub rsp, 48
lea rbx, [rsp + 32]
mov qword ptr [rsp + 16], rbx
mov qword ptr [rsp + 8], 16
lea rdi, [rsp + 16]
lea rsi, [rsp + 8]
xor edx, edx
call std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_create(unsigned long&, unsigned long)
mov qword ptr [rsp + 16], rax
mov rcx, qword ptr [rsp + 8]
mov qword ptr [rsp + 32], rcx
movups xmm0, xmmword ptr [rip + .L.str]
movups xmmword ptr [rax], xmm0
mov qword ptr [rsp + 24], rcx
mov rax, qword ptr [rsp + 16]
mov byte ptr [rax + rcx], 0
mov rdi, qword ptr [rsp + 16]
cmp rdi, rbx
je .LBB0_3
call operator delete(void*)
.LBB0_3:
xor eax, eax
add rsp, 48
pop rbx
ret
mov rdi, rax
call _Unwind_Resume
.L.str:
.asciz "ABCDEFGHIJKLMNOP"
当使用相同的-O3
编译时,我不明白为什么它无法识别a
仍然未被使用,尽管字符串多了一个字节。这个问题与gcc 9.1和clang 8.0有关(在线:https://gcc.godbolt.org/z/p1Z8Ns),因为在我的观察中,其他编译器要么完全删除未使用的变量(ellcc),要么生成代码,而不考虑字符串的长度。
a
声明为 volatile,你会发现这两个字符串被不同地处理。其中最长的似乎被分配在堆上。https://gcc.godbolt.org/z/WUuJIB - Davide Spatarostring_view
,它仍然可以优化掉更长的字符串: https://godbolt.org/z/AAViry - Ted Lyngmo-stdlib=libc++
参数;-) - Daniel Langr