用于操作原始内存的正确数据类型
Correct data type for manipulating raw memory
>我有一个便于编码/解码原始内存的类。 我最终存储了一个void
指针,指向内存和被引用的字节数。 我担心混叠问题以及使编码正确的移位操作。 本质上,对于WHAT_TYPE
,我应该使用char
,unsigned char
,int8_t
,uint8_t
,int_fast8_t
,uint_fast8_t
,int_least8_t
或uint_least8_t
? 规范中是否有明确的答案?
class sample_buffer {
size_t index; // For illustrative purposes
void *memory;
size_t num_bytes;
public:
sample_buffer(size_t n) :
index(0),
memory(malloc(n)),
num_bytes(memory == nullptr ? 0 : n) {
}
~sample_buffer() {
if (memory != nullptr) free(memory);
}
void put(uint32_t const value) {
WHAT_TYPE *bytes = static_cast<WHAT_TYPE *>(memory);
bytes[index] = value >> 24;
bytes[index + 1] = (value >> 16) & 0xFF;
bytes[index + 2] = (value >> 8) & 0xFF;
bytes[index + 3] = value & 0xFF;
index += 4;
}
void read(uint32_t &value) {
WHAT_TYPE const *bytes = static_cast<WHAT_TYPE const *>(memory);
value = (static_cast<uint32_t>(bytes[index]) << 24) |
(static_cast<uint32_t>(bytes[index + 1]) << 16) |
(static_cast<uint32_t>(bytes[index + 2]) << 8) |
(static_cast<uint32_t>(bytes[index + 3]);
index += 4;
}
};
在 C++17 中:std::byte
.正是出于这个原因,专门创建了此类型,以传达所有正确的语义含义。此外,它具有您需要对原始数据使用的所有运算符(如示例中的<<
(,但没有您不会使用的运算符。
C++17之前:unsigned char
.该标准将对象表示定义为unsigned char
序列,因此它只是一个不错的类型。此外,正如Mooing Duck正确建议的那样,使用unsigned char*
可以防止由于错误地使用引用原始字节的char*
而导致的许多错误,就好像它是一个字符串并将其传递给像strlen
这样的函数。
如果你真的不能使用unsigned char
,那么你应该使用char
。unsigned char
和 char
都是允许您别名的类型,因此其中任何一种都优先于任何其他整数类型。
相关文章:
- 防止主数据类型C++的隐式转换
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在C++中打印指向不同基元数据类型的指针的内存地址
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何计算数据类型的范围,例如int
- C++中数据类型修饰符的顺序
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 特定数据类型的模板类
- 具有多个模板的模板函数,用于特定数据类型(如字符串)?
- 如果一个变量在它之前释放了另一个(相同的数据类型)变量,如何将其分配给内存?
- 内存效率:模板与基本数据类型
- 将分配的内存与基本数据类型一起使用时,是否需要新放置? std::complex?
- 数据对齐:限制内存地址为数据类型大小倍数的原因
- 在编译时检查特征类型保存的数据在内存中是否连续
- 用于操作原始内存的正确数据类型
- 使用QStandardItem传输自定义数据(类型*)时内存泄漏
- 在c++中,枚举数据类型消耗多少内存
- 使用小数据类型是否会减少内存使用(来自内存分配而不是效率)
- 如何在C++中确定标准库字符串或其他非基本数据类型在内存中的大小
- 在数据类型由传入值确定的函数中分配内存