I'm designing a Buffer class whose purpose is to represent a chunk of memory.
My underlying buffer is a char*
(well, a boost::shared_array<char>
actually, but it doesn't really matter).
I'm stuck at deciding what prototype to choose for my constructor:
Should I go with:
Buffer(const void* buf, size_t buflen);
Or with:
Buffer(const char* buf, size_t buflen);
Or something else ?
What is usually done, and why ?
Why do we use a void pointer in C programs? We use the void pointers to overcome the issue of assigning separate values to different data types in a program. The pointer to void can be used in generic functions in C because it is capable of pointing to any data type.
The void pointer in C is a pointer which is not associated with any data types. It points to some data location in the storage means points to the address of variables. It is also called general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.
Returns a string containing the characters in this buffer. Wraps a character sequence into a buffer.
Now, we want to assign the void pointer to integer pointer, in order to do this, we need to apply the cast operator, i.e., (int *) to the void pointer variable. This cast operator tells the compiler which type of value void pointer is holding.
API interface is more clear for user, if buffer has void* type, and string has char* type. Compare memcpy and strcpy function definitions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With