void* func(void* arg)

closed account (Nwb4iNh0)
does this function mean that the data type we will pass is unknow and the return will be pointer?
how this func work

 
void* func(void* arg)
Yes.

Though to actually be useful, func already knows how to cast the void *arg back to something meaningful.

Hello.

Q1: does this function mean that the data type we will pass is unknow and the return will be pointer?

I think the type of data is unknown.

On StackOverflow, we can find similar question. The Accepted answer said "A pointer to void is a "generic" pointer type.".

Q2: How this func work?

It depends on how the writer of this function func designs it. We can design a "generic function" using void *. The library function qsort is a good example. The following is qsort declaration.

1
2
void qsort (void* base, size_t num, size_t size,
            int (*compar)(const void*,const void*));


Though we don't know the data type, we also sort this array base.

reference:
similar question: https://stackoverflow.com/questions/11626786/what-does-void-mean-and-how-to-use-it
qsort: https://www.cplusplus.com/reference/cstdlib/qsort/
void * is more C than C++. I can't think of a lot of places where you would need one in C++ these days. Older code (pre C++ 2011) may use it more frequently. I have not used one, outside of showing an example or using a C routine, in a very long time.

what it really is... it is saying that you have a memory location that you own and want to manipulate, but you do not know what is located there. Sometimes that is ok, just like file.write() thinks everything is just a char* (it could just as easily have accepted a void* and cast it to char* internally) and does not care about the details because it handles things at a byte level. Threads use them too, or some thread libraries (pre c++ adding its own solution) -- they represent the parameters to the thread function and are passed through via the void * (unused and untouched by the threading library itself). The threading function, which the programmer wrote, knows what to do to extract the original data back out of there. This allows the threading function to pass ANYTHING through without caring what it is or needing templates or other exotic solutions just to do nothing except copy an address.

the above (a pass-unknown-thing-through system) is about all I can think of for using one in modern c++, and honestly, there are probably better ways to do that without the void* now.
Last edited on
Topic archived. No new replies allowed.