Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

c++ - When to use a void pointer?

I understand the use of void pointer for malloc implementation.

void* malloc  ( size_t size );

Can anyone suggest other reasons or provide some scenarios where it is useful in practice.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One good scenario void* use is when you want to implement any generic ADT's, in case you just don't know what datatype it going to keep and deal with. For example, a linked list like the following:

typedef struct node_t node;
struct
{
    void* data;
    node* prev, next;
} node_t;

typedef struct list_t list;
typedef void* (func)(void*) cpy_func;
typedef void (func)(void*) del_func;
struct
{
   node* head, tail, curr;
   cpy_func copy;
   del_func delete;
} list_t;

initializeLinkedList(cpy_func cpy, del_func del);
//here you keep going defining an API

Here for example you will pass in initialization function pointers to other functions which will be capable of copying your datatype to your list and freeing it afterwards. So by using void* you make your list more generic.

I think void* remained in C++ only because of backward compatibility, since in C++ you have more safe and sophisticated ways to achieve the same result like templates, functors, etc., and you don't need to use malloc while programming C++.

Regarding C++, I don't have any specific useful examples.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...