Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a legitimate use for void*?

Tags:

c++

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.

like image 366
magu_ Avatar asked Dec 14 '15 17:12

magu_


People also ask

What is void * used for?

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.

What is the use of void pointers?

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.

What does void * p mean?

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 );

Can you free a void *?

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.


1 Answers

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*

like image 122
Basile Starynkevitch Avatar answered Sep 23 '22 03:09

Basile Starynkevitch