Union vs. static_cast(void *) [英] Union vs. static_cast(void*)
问题描述
我正在编写代码,直到现在我正在使用这样的结构:
I'm writing code and until now I was using structures like this:
struct s{
enum Types { zero = 0, one, two };
unsigned int type;
void* data;
}
我需要一些通用结构来存储不同类的数据,我想使用它在std :: vector,所以这就是为什么我不能使用模板的原因。更好的选择:联合或void指针?
I needed some generic structure to store data from different classes and I wanted to use it in std::vector, so that's reason why I can't use templates. What's better option: unions or void pointers?
Void指针只分配我需要的空间,但是c ++是强类型语言,使用那些数据不是c ++代码的设计方式。正如我所读,void指针不应该使用,除非没有替代。
Void pointer allocates only as much space as I need, but c++ is strong typed language for some reason and casting everywhere I need to use those data is not the way c++ code should be designed. As I read, void pointers shouldn't be used unless there's no alternative.
这个替代方法可以是联合。它们带有c ++并为每个成员使用相同的内存空间,非常像void指针。但是,他们来到价格分配的空间是联合中最大元素的大小,在我的情况下,大小之间的差异是大的。
That alternative could be Unions. They comes with c++ and uses the same memory space for every member, very much like void pointers. However they come at price - allocated space is the size of largest element in union, and in my case differences between sizes are big.
这是相当风格和正确的语言使用问题,因为这两种方法都能完成我需要做的事情,但我不能决定是否很好的风格化的c ++代码可以支付浪费的内存(即使内存这些天不是一个大问题)。
This is rather stylistic and "correct language using" problem, as both ways accomplish what I need to do, but I can't decide if nicely stylized c++ code can pay for that wasted memory (even though memory these days isn't a big concern).
推荐答案
考虑 boost :: any
或 boost :: variant
。
在决定使用哪一个之前,请先看一下比较:
And before deciding which one to use, have a look at the comparison:
- Boost.Variant vs. Boost.Any
希望能帮助您做出正确的决定。选择一个,并从标准库中存储对象的任何容器, std :: vector< boost :: any>
, std ::向量< boost :: variant>
或任何其他。
Hopefully, it will help you to make the correct decision. Choose one, and any of the container from the standard library to store the objects, std::vector<boost::any>
, std::vector<boost::variant>
, or any other.
这篇关于Union vs. static_cast(void *)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!