rwb
rwb

Reputation: 621

Cast char array struct vector to a POD vector?

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;

Upvotes: 2

Views: 576

Answers (2)

Darinth
Darinth

Reputation: 510

No, this is not safe and generally not recommended because compilers aren't required to operate in a method that allows it. With that said, I've found exactly one reason to ever do this (very recently as well) and that is a variant of the pimpl idiom where I wanted to avoid pointers so that all of my data access could avoid the need to allocate memory for, deallocate memory for, and dereference the extra pointer. That code isn't in production yet and I'm still keeping an eye on that section of code to make sure that it doesn't start causing any other problems.

Unless you're generating code that has to be Extremely optimized, I would recommend finding some other way of doing whatever it is you need to do.

Upvotes: 1

John Dibling
John Dibling

Reputation: 101484

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

Upvotes: 4

Related Questions