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

后端 未结 4 559
灰色年华
灰色年华 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条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-08 03:14

    What is the motivation for std::byte?

    Quoting from the original paper;

    Many programs require byte-oriented access to memory. Today, such programs must use either the char, signed char, or unsigned char types for this purpose. However, these types perform a “triple duty”. Not only are they used for byte addressing, but also as arithmetic types, and as character types. This multiplicity of roles opens the door for programmer error - such as accidentally performing arithmetic on memory that should be treated as a byte value - and confusion for both programmers and tools.

    In essence, std::byte is there to "replace" the use of char-types when required to deal with raw memory as bytes, it would be safe to assert that this is applicable when used by-value, by-refernce, pointers and in containers.

    std::byte does not have the same connotations as a char; it's about raw memory, not characters

    Correct, so std::byte should be preferred over char-types when dealing with bytes in memory (as in, an array of bytes). Some lower level protocol data manipulation immediately comes to mind.

    What is a good rule of thumb, for the days of std::byte, regarding when to prefer it over void * and when it's the other way around?

    I would argue that similar guides apply now as they did previously. When dealing with raw blocks of memory, where the byte addressability is required, char * etc. would have been preferred over void *, I think the same logic applies now, but prefer byte * over char *. A char * is better for a character sequences.

    If the desire is to pass around a pointer opaquely, the void * probably still best fits the problem. void * essentially means "point to anything", but the anything is still something, we are just not saying what yet.

    Further, the types uintptr_t (and intptr_t) would probably factor in as alternatives, depending of course on the desired application.

    ... I mostly mean new code where you get to choose all the types.

    New code generally has very limited use of void * outside of compatibility (where you don't get to choose the type). If you need byte based processing then favour byte *.

提交回复
热议问题