With std::byte standardized, when do we use a void* and when a byte*?

后端 未结 4 560
灰色年华
灰色年华 2021-02-08 02:10

C++17 will include std::byte, a type for one atomically-addressable unit of memory, having 8 bits on typical computers.

Before this standardization, there is already a b

4条回答
  •  萌比男神i
    2021-02-08 02:58

    (This is a potential rule of thumb which comes off the top of my head, not condoned by anyone.)

    Rule of thumb: When to use which kind of pointer?

    • Use char * for sequences of textual characters, not anything else.
    • Use void * in type-erasure scenarios, i.e. when the pointed-to data is typed, but for some reason a typed pointer must not be used or it cannot be determined whether it's typed or not.
    • Use byte * for raw memory for which there is no indication of it holding any typed data.

    An exception to the above:

    • Also use void */unsigned char */char * when older or non-C++ forces you and you would otherwise use byte * - but wrap that with a byte *-based interface as tightly as you can rather than exposing it to the rest of your C++ code.

    Examples

    void * my_custom_malloc(size_t size) - wrong
    byte * my_custom_malloc(size_t size) - right

    struct buffer_t { byte* data; size_t length; my_type_t data_type; } - wrong
    struct buffer_t { void* data; size_t length; my_type_t data_type; } - right

提交回复
热议问题