void* or char* for generic buffer representation?
For the constructor and other API functions, the advantage of void*
is that it allows the caller to pass in a pointer to any type without having to do an unnecessary cast. If it makes sense for the caller to be able to pass in any type, then void*
is preferable. If it really only makes sense for the caller to be able to pass in char*
, then use that type.
C++17
C++17 introduced std::byte
specifically for this.
Its definition is actually simple: enum class byte : unsigned char {};
.
I generally used unsigned char
as the underlying structure (don't want signedness to mess up with my buffer for I know what reason). However I usually typedefed it:
// C++11using byte = unsigned char;// C++98typedef unsigned char byte;
And then refer to it as byte*
which neatly conveys the meaning in my opinion, better than either char*
or void*
at least.