何时在C ++中使用void * [英] when to use void* in c++

查看:197
本文介绍了何时在C ++中使用void *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用void*包裹一下头部,适当地使用它,以及是否有任何可能滥用的用途,我应该知道. (意思是很酷,没错).

I am trying to wrap my head about a void* and what is appropriate use of it and if there is any potentially abusive use I should know about. (Meaning something cool, not wrong).

我不知道如何以及为什么使用void*.如果我了解我需要将当前指针转换为void*,然后在我想使用它时转换回原始指针...?

I dont understand how and why to use a void*. If I am understanding I would need to cast my current pointer to a void* and then cast back to the original when I wanted to use it...?

这为什么有益?不要使事情变得通用,因为我需要知道传入哪种类型的void*来进行强制转换...

Why is this beneficial? Not to make things generic because I need to know what type of void* was passed in to do the cast...

任何人都可以帮助我理解void*

Can anyone help me understand void*

推荐答案

C 中,通常使用void *创建通用集合.例如,如果您想要一个通用链接列表,则可以编写如下内容:

In C it's fairly common to use void * to create a generic collection. For example, if you wanted a generic linked list, you might write something like:

typedef struct node  { 
    void *data;
    struct node *next;
} node;

然后,您可以创建一个foo的链接列表,另一个bar的链接列表,依此类推.

Then you could create one linked list of foo, another linked list of bar, and so on.

但是,在C ++中,这很少有用.在典型情况下,您希望将等效代码编写为模板:

In C++, however, this is rarely useful. In a typical case, you'd want to write equivalent code as a template instead:

template <typename T>
class node { 
     T data;
     node *next;
};

使用较早的编译器,可以通过结合使用两种技术来减少生成的代码.在这种情况下,您将使用一组指针来使存储无效,然后有一个模板前端,用于存储数据时将T *强制转换为void *,并在检索数据时从void *返回到T *.

With older compilers, you could reduce the generated code by combining the two techniques. In this case, you'd use a collection of pointers to void to store the data, then have a template front-end that just handled casting T * to void * when you stored the data, and back from void * to T * when you retrieved the data.

编译器/链接器的改进使该技术(几乎是?)完全过时了.较早的编译器会为您实例化模板的每种类型生成单独的代码,即使实例化类型无关紧要.当前的编译器(或工具链,无论如何-相当一部分是由链接器处理的)可以识别相同的代码序列,并将它们自动合并在一起.

Improvements in compilers/linkers have rendered this technique (almost?) entirely obsolete though. Older compilers would generate separate code for each type over which you instantiated your template, even where the instantiation type was irrelevant. Current compilers (or toolchains, anyway -- quite a bit of this is really handled by the linker) identify the identical code sequences, and merge them together automatically.

最重要的是:除非需要C兼容性,或者正在编写替换的operator new/operator delete,否则在编写良好的C ++中通常很少使用void *.

Bottom line: unless you need C compatibility, or you're writing a replacement operator new/operator delete, use of void * in well written C++ is usually pretty rare.

这篇关于何时在C ++中使用void *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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