用于操作原始内存的正确数据类型

Correct data type for manipulating raw memory

本文关键字:数据类型 内存 操作 原始 用于      更新时间:2023-10-16

>我有一个便于编码/解码原始内存的类。 我最终存储了一个void指针,指向内存和被引用的字节数。 我担心混叠问题以及使编码正确的移位操作。 本质上,对于WHAT_TYPE,我应该使用charunsigned charint8_tuint8_tint_fast8_tuint_fast8_tint_least8_tuint_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,那么你应该使用charunsigned charchar 都是允许您别名的类型,因此其中任何一种都优先于任何其他整数类型。