提问人:Luchian Grigore 提问时间:1/22/2013 最后编辑:Luchian Grigore 更新时间:1/22/2013 访问量:174
为什么 MSVC 不针对 char 或 const char* 优化 cout,而是针对 int 优化?
Why doesn't MSVC optimize cout for char or const char* but it does for int?
问:
比较代码:
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
版本优化得更好。
答:
1赞
MSalters
1/22/2013
#1
从运算符名称来看:因为一个是成员,另一个是自由函数。
评论
0赞
Lol4t0
1/22/2013
@LuchianGrigore和调用转化是不同的。
8赞
Mike Seymour
1/22/2013
#2
的一些重载(包括 for ,但不是 或 )是 的成员;有些是非成员函数,作为其第一个参数。operator<<
int
char
const char*
std::ostream
std::ostream&
Microsoft 的编译器对成员函数和非成员函数使用不同的调用约定。我猜您正在为 32 位 Windows 构建。在这种情况下,成员函数将使用约定,其中在寄存器中传递,其余参数在堆栈上传递;非成员函数使用约定,其中所有参数都在堆栈上传递。thiscall
this
ecx
cdecl
评论
0赞
Luchian Grigore
1/22/2013
是否指定了哪些是成员,哪些不是?
2赞
Mike Seymour
1/22/2013
@LuchianGrigore:是的,在C++11 27.7.3.6.2(以及27.7.3.1中的定义)。对于除 (signed or unsigned) 和 之外的所有算术类型,该成员都重载,对于 。basic_ostream
char
charT
const void*
0赞
David
1/22/2013
为什么它没有因有符号/无符号而重载?char
0赞
Mike Seymour
1/22/2013
@Dave:我猜他们作为非成员重载的原因与重载选择规则有关(避免歧义,或强制选择特定的“最佳”重载),但我不知道具体原因是什么。
上一个:为什么不能用结构定义模板?
评论
const int
constexpr