将字符数组struct向量转换为POD向量? [英] Cast char array struct vector to a POD vector?

查看:302
本文介绍了将字符数组struct向量转换为POD向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,如果我想创建一个仅用于保存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:


  1. 也许作者想要一个抽象数据结构

  2. 也许作者想要一个不透明的数据结构。在这种情况下,我将使用pimpl成语的一些变体,其中 void * (或 char * )呈现

  3. 也许作者想要某种内存池。最好的方法是分配 char 的大缓冲区,然后使用placement-new在其中构造真实对象。

  1. 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.
  2. Maybe the author wanted an opaque data structure. In that case I would employ some variant of the pimpl idiom, where the void* (or char*) presented to the user actually points to some real data type.
  3. 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屋!

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