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

后端 未结 4 482
灰色年华
灰色年华 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:10

    First, void * still makes sense when you have to use a C library function or generally speaking to use any other extern "C" compatible function.

    Next a std::byte array still allows individual access to any of its elements. Said differently this is legal:

    std::byte *arr = ...;
    arr[i] = std::byte{0x2a};
    

    It makes sense if you want to be able to allow that low level access, for example if you want to manually copy all or parts of the array.

    On the other hand, void * is really an opaque pointer, in the sense that you will have to cast it (to a char or byte) before being able to access its individual elements.

    So my opinion is that std::byte should be used as soon as you want to be able to address elements of an array or move a pointer, and void * still makes sense to denote an opaque zone that will only be passed (hard to actually process a void *) as a whole.

    But real use case for void * should become more and more unusual in modern C++ at least at high level, because those opaque zones should normally be hidden in higher level classes coming with methods to process them. So IMHO void * should in the end be limited to C (and older C++ versions) compatibiliy, and low level code (such as allocating code).

提交回复
热议问题