Is there a legitimate use of void*
in C++? Or was this introduced because C had it?
Just to recap my thoughts:
Input: If we want to allow multiple input types we can overload functions and methods, alternatively we can define a common base class, or template (thanks for mentioning this in the answers). In both cases the code get's more descriptive and less error prone (provided the base class is implemented in a sane way).
Output: I can't think of any situation where I would prefer to receive void*
as opposed to something derived from a known base class.
Just to make it clear what I mean: I'm not specifically asking if there is a use-case for void*
, but if there is a case where void*
is the best or only available choice. Which has been perfectly answered by several people below.
void (C++)When used as a function return type, the void keyword specifies that the function doesn't return a value. When used for a function's parameter list, void specifies that the function takes no parameters.
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.
which basically: declares a variable named p which is a pointer to type void (and pointers to void are compatible with pointers to any object type without requiring any explicit cast, including pointers to pointers to void — which is the type of &p );
yes it is safe. Show activity on this post. In one case, malloc and free match, and in the other the allocated memory is returned. There are also secondary resources, and the constructor and destructor match.
void*
is at least necessary as the result of ::operator new
(also every operator new
...) and of malloc
and as the argument of the placement new
operator.
void*
can be thought as the common supertype of every pointer type. So it is not exactly meaning pointer to void
, but pointer to anything.
BTW, if you wanted to keep some data for several unrelated global variables, you might use some std::map<void*,int> score;
then, after having declared global int x;
and double y;
and std::string s;
do score[&x]=1;
and score[&y]=2;
and score[&z]=3;
memset
wants a void*
address (the most generic ones)
Also, POSIX systems have dlsym and its return type evidently should be void*
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