将字符数组struct向量转换为POD向量? [英] Cast char array struct vector to a POD vector?
问题描述
说,如果我想创建一个仅用于保存POD结构和常规数据类型的向量类型。我可以执行以下操作吗?它看起来非常不安全,但它的工作原理。如果是,可能会出现什么样的问题?
Say, if I want to create a vector type of only for holding POD structures and regular data types. Can I do the following? It looks very unsafe but it works. If it is, what sort of issues might arise?
template <size_t N>
struct Bytes {
char data[N];
};
std::vector<Bytes<sizeof(double)> > d_byte_vector;
std::vector<double>* d_vectorP = reinterpret_cast<std::vector<double>*>(&d_byte_vector);
for (int i=0;i<50;i++) {
d_vectorP->push_back(rand()/RAND_MAX);
}
std::cout << d_vectorP->size() << ":" << d_byte_vector.size() << std::endl;
推荐答案
不, em>。特定的编译器可以做一些特定的C ++方言的保证,但根据标准,你通过实例化一个 char
的数组并假装它实际上是一个完全不同的东西不相关。
No, this is not safe. Specific compilers may make some guarantee that is particular to that dialect of C++, but according to the Standard you evoke Undefined Behavior by instantiating an array of char
and pretending it's actually something else completely unrelated.
通常,当我看到这样的代码时,作者要做三件事之一,错过了一个正确的方法:
Usually when I see code like this, the author was going for one of three things and missed one of the Right Ways to go about it:
- 也许作者想要一个抽象数据结构。
- 也许作者想要一个不透明的数据结构。在这种情况下,我将使用pimpl成语的一些变体,其中
void *
(或char *
)呈现 - 也许作者想要某种内存池。最好的方法是分配
char
的大缓冲区,然后使用placement-new在其中构造真实对象。
- Maybe the author wanted an abstract data structure. A better way to go about that is to use an abstract base class, and move the implementation elsewhere.
- Maybe the author wanted an opaque data structure. In that case I would employ some variant of the pimpl idiom, where the
void*
(orchar*
) presented to the user actually points to some real data type. - Maybe the author wanted some kind of memory pool. The best way to accomplish that is to allocate a large buffer of
char
, and then use placement-new to construct real objects within it.
这篇关于将字符数组struct向量转换为POD向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!