当询问C中常见的未定义行为时,灵魂比我提到的严格别名规则更加开明.
他们在说什么?
根据C和C++ , CHAR_BIT >= 8.
但无论何时CHAR_BIT > 8,uint8_t甚至都不能表示为8位.
它必须更大,因为它CHAR_BIT是系统上任何数据类型的最小位数.
什么样的系统可以uint8_t合法地定义为除了以外的类型unsigned char?
(如果C和C++的答案不同,那么我想知道两者.)
鉴于这个C++ 11程序,我应该期待看到一个数字还是一个字母?还是没有期望?
#include <cstdint>
#include <iostream>
int main()
{
int8_t i = 65;
std::cout << i;
}
Run Code Online (Sandbox Code Playgroud)
标准是否指定此类型是否可以是字符类型?
目前 在 已经 问题在这里问#1 为什么 basic_fstream<uint8_t>不工作.答案说这char_traits只是专门用于char和wchar_t(加上char16_t,char32_t在C++ 11中),你应该坚持basic_fstream<char>阅读二进制数据并在需要时投射它.
好吧,这还不够好!:)
没有任何答案(我能找到)说明如何专门化char_traits<uint8_t>和使用basic_fstream模板,或者甚至可能.所以我想我会尝试自己实现它.
在Windows 7 64位上使用Visual Studio Express 2013 RC并在Kubuntu GNU/Linux 13.04 64位上使用g ++ - 4.7时,以下编译没有错误.但是它会在运行时抛出std :: bad_cast异常.我没有访问clang ++和libc ++来测试这个组合.
#include <cinttypes>
#include <cstring>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <locale>
#ifdef _WIN32
#define constexpr
#define NOEXCEPT throw()
#else
#define NOEXCEPT noexcept
#endif
// Change this to char and it works.
using byte_type …Run Code Online (Sandbox Code Playgroud) 对不起,如果我的怀疑太幼稚。但我有一个类型转换难度std::atomic要char*类型。是强制转换std::atomic to char有效吗?
我可以写这样的类型转换变量。我确信当线程试图将变量写入变量时不会有多线程读/写操作(我知道,当该变量没有并发访问时,就不需要使用原子)。
std::atomic<uint8_t>* data_;
char *data = reinterpret_cast<char*>(data_);
*data |= mask;
Run Code Online (Sandbox Code Playgroud)
安全吗?
编辑:我不确定是否值得一提。在我的代码中
char *raw;
// variable raw is allocated
std::atomic<uint8_t>* data_ = reinterpret_cast<std::atomic<uint8_t>*>(raw);
Run Code Online (Sandbox Code Playgroud)
上面是std::atomic< uint8_t>创建方法的方式(作为char和type强制转换为std :: atomic类型)。
谢谢 :)
c++ ×4
c ×2
c++11 ×2
char-traits ×1
g++ ×1
iostream ×1
stdatomic ×1
type-punning ×1
types ×1
uint8t ×1