问题描述
如果你试图找到一个volatile类型的指针,即使是一个volatile字符指针,你通常期望cout打印字符串,你会改为简单的得到'1'(假设指针不为null我想)。假设输出流运算符<<是专门为易失性指针的模板,但我的问题是,为什么?
If you try to cout a pointer to a volatile type, even a volatile char pointer where you would normally expect cout to print the string, you will instead simply get '1' (assuming the pointer is not null I think). I assume output stream operator<< is template specialized for volatile pointers, but my question is, why? What use case motivates this behavior?
示例代码:
#include <iostream>
#include <cstring>
int main()
{
char x[500];
std::strcpy(x, "Hello world");
int y;
int *z = &y;
std::cout << x << std::endl;
std::cout << (char volatile*)x << std::endl;
std::cout << z << std::endl;
std::cout << (int volatile*)z << std::endl;
return 0;
}
输出:
Hello world
1
0x8046b6c
1
推荐答案
ostream :: operator<<
有以下重载:
ostream& operator<< (bool val );
ostream& operator<< (const void* val );
当你传递一个volatile指针时,第二个重载不能应用,因为volatile指针不能被转换到非易失性而没有显式铸造。但是,任何指针都可以转换为bool,所以选择第一个重载,你看到的结果是1或0.
When you pass in a volatile pointer, the second overload can't apply because volatile pointers cannot be converted to non-volatile without an explicit cast. However, any pointer can be converted to bool, so the first overload is chosen, and the result you see is 1 or 0.
所以真正的原因不是代表标准委托的有意决定,但简单地说,该标准没有指定一个带有易失性指针的重载。
So the real reason for this is not an intentional decision on behalf of the standards committe, but simply that the standard does not specify an overload that takes a volatile pointer.
这篇关于为什么std :: cout将volatile指针转换为bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!