gpt4 book ai didi

c++ - 为什么 MSVC 不为 char 或 const char* 优化 cout 而为 int 优化?

转载 作者:太空狗 更新时间:2023-10-29 23:46:00 26 4
gpt4 key购买 nike

比较代码:

    const char x = 'a';
std::cout<< x;
00C31000 mov eax,dword ptr [__imp_std::cout (0C32054h)]
00C31005 push eax
00C31006 call std::operator<<<std::char_traits<char> > (0C310B0h)
00C3100B add esp,4

    const int x = 'a';
std::cout<< x;
00271000 mov ecx,dword ptr [__imp_std::cout (272048h)]
00271006 push 61h
00271008 call dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (272044h)]

    const char* x = "a";
std::cout<< x;
00071000 mov eax,dword ptr [__imp_std::cout (72058h)]
00071005 push eax
00071006 call std::operator<<<std::char_traits<char> > (710B0h)
0007100B add esp,4

似乎 const int 版本比 const char* 和(更令人惊讶的)const char 优化得更好> 版本。 问题 - 为什么生成的代码存在差异?

最佳答案

一些重载 operator<< (包括 int ,但 charconst char* )是 std::ostream 的成员;有些是采用 std::ostream& 的非成员函数作为他们的第一个参数。

Microsoft 的编译器对成员函数和非成员函数使用不同的调用约定。我猜您正在为 32 位 Windows 构建。在这种情况下,成员函数将使用 thiscall惯例,其中 this在寄存器中传递 ecx其余参数在堆栈上传递;和非成员函数使用 cdecl约定,其中所有参数都在堆栈上传递。

关于c++ - 为什么 MSVC 不为 char 或 const char* 优化 cout 而为 int 优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14442563/

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