当使用一个空指针? [英] When to use a void pointer?

查看:142
本文介绍了当使用一个空指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解的malloc实现使用空指针。

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.

感谢

推荐答案

一个好的方案无效* 的使用是当你想实现任何通用的ADT的,如果你只是不知道它要保持和处理什么数据类型。例如,一个链接列表如下所示:

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

这里有个例子,你会在初始化函数指针传递给其他的功能,这将能够复制你的数据类型,以你的清单,随后释放它的。因此,通过使用无效* 你让你的列表更通用。

我觉得无效* 留在C ++中唯一向后兼容的原因,因为在C ++中,你有更多的安全和复杂的方式来实现类似的模板,仿函数等相同的结果,而你并不需要使用malloc在编程C ++。

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++.

对于C ++,我没有任何具体有用的例子。

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

这篇关于当使用一个空指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆