I am trying to wrap my head about a void*
and what is appropriate use of it and if there is any potentially abusive use I should know about. (Meaning something cool, not wrong).
I dont understand how and why to use a void*
. If I am understanding I would need to cast my current pointer to a void*
and then cast back to the original when I wanted to use it...?
Why is this beneficial? Not to make things generic because I need to know what type of void*
was passed in to do the cast...
Can anyone help me understand void*
void*
is a memory address without a type. It's useful when the code around it has some other way of knowing what type it is working with (for example, memchr
needs to have the size of the memory area passed in addition to the address).
In C it's fairly common to use void *
to create a generic collection. For example, if you wanted a generic linked list, you might write something like:
typedef struct node {
void *data;
struct node *next;
} node;
Then you could create one linked list of foo
, another linked list of bar
, and so on.
In C++, however, this is rarely useful. In a typical case, you'd want to write equivalent code as a template instead:
template <typename T>
class node {
T data;
node *next;
};
With older compilers, you could reduce the generated code by combining the two techniques. In this case, you'd use a collection of pointers to void to store the data, then have a template front-end that just handled casting T *
to void *
when you stored the data, and back from void *
to T *
when you retrieved the data.
Improvements in compilers/linkers have rendered this technique (almost?) entirely obsolete though. Older compilers would generate separate code for each type over which you instantiated your template, even where the instantiation type was irrelevant. Current compilers (or toolchains, anyway -- quite a bit of this is really handled by the linker) identify the identical code sequences, and merge them together automatically.
Bottom line: unless you need C compatibility, or you're writing a replacement operator new
/operator delete
, use of void *
in well written C++ is usually pretty rare.
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