为什么 std::cout 将 volatile 指针转换为 bool?

时间:2023-02-23
本文介绍了为什么 std::cout 将 volatile 指针转换为 bool?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如果您尝试 cout 指向易失性类型的指针,即使是您通常希望 cout 打印字符串的易失性字符指针,您只会得到1"(假设我认为该指针不为空).我假设输出流操作符<<模板是专门用于 volatile 指针的,但我的问题是,为什么?什么用例会激发这种行为?

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<< has the following overloads, among others:

ostream& operator<< (bool val );
ostream& operator<< (const void* val );

当您传入 volatile 指针时,无法应用第二个重载,因为 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.

因此,真正的原因不是代表标准委员会的有意决定,而只是标准没有指定采用 volatile 指针的重载.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:指针是否保证在 C++ 中的“删除"之后保留其值? 下一篇:我应该存储整个对象,还是在容器中存储指向对象的指针?

相关文章

最新文章