Is the following valid C++? It's an alternative way of implementing a variable length tail to a flat structure. In C this is commonly done with the struct hack
struct Str
{
Str(int c) : count(c) {}
size_t count;
Elem* data() { return (Elem*)(this + 1); }
};
Str* str = (Str*)new char[sizeof(Str) + sizeof(Elem) * count];
new (str) Str(count);
for (int i = 0; i < count; ++i)
new (str->data() + i) Elem();
str->data()[0] = elem0;
str->data()[1] = elem1;
// etc...
I ask this in response to the following related question
No, it is not valid:
Elem might have different alignment than Str
, so (reinterpret_)casting Str+1
to Elem*
might or might not give you a valid pointer, and acccessing might give undefined behavior.
But after all, why would you want to do something like that?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With