uint8_t iostream行为

Joh*_*ann 13 c++ iostream c++11

摘要:我期待代码:cout << uint8_t(0); 打印"0",但它不打印任何东西.

长版本:当我尝试将uint8_t对象流式传输到cout时,我会使用gcc获得奇怪的字符.这是预期的行为吗?可能是因为uint8_t是某些基于字符的类型的别名吗?请参阅代码示例中的编译器/系统说明.

// compile and run with:
// g++ test-uint8.cpp -std=c++11 && ./a.out
//                    -std=c++0x (for older gcc versions)
/**
 * prints out the following with compiler:
 *     gcc (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2)
 * on the system:
 *     Linux 3.7.9-101.fc17.x86_64
 * Note that the first print statement uses an unset uint8_t
 * and therefore the behaviour is undefined. (Included here for
 * completeness)

> g++ test-uint8.cpp -std=c++11 && ./a.out
>>>?<<<    >>>194<<<
>>><<<    >>>0<<<
>>><<<    >>>0<<<
>>><<<    >>>0<<<
>>><<<    >>>1<<<
>>><<<    >>>2<<<

 *
 **/

#include <cstdint>
#include <iostream>

void print(const uint8_t& n)
{
    std::cout << ">>>" << n                 << "<<<    "
              << ">>>" << (unsigned int)(n) << "<<<\n";
}

int main()
{
    uint8_t a;
    uint8_t b(0);
    uint8_t c = 0;
    uint8_t d{0};
    uint8_t e = 1;
    uint8_t f = 2;
    for (auto i : {a,b,c,d,e,f})
    {
        print(i);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 15

uint8_t是别名unsigned char,并且iostream对字符有特殊的重载,打印字符而不是格式化数字.

转换为整数会抑制这种情况.


Pet*_*ker 7

可能是因为uint8_t是某些基于字符的类型的别名吗?

绝对.如果存在这样的类型,则必须是内置8位无符号整数类型的typedef.由于只有两种可能的8位无符号整数类型,char对于将其视为无符号的编译器unsigned char,它必须是其中之一.除了char大于8位的系统外,在这种情况下它不存在.

  • 允许实现提供更多扩展的整数类型,这些类型不是标准整数类型的别名.所以我认为技术上'uint8_t`*可能*是非字符类型,尽管通常不是. (2认同)