Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a C++ alternative to the struct hack?

Tags:

c++

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

like image 830
john Avatar asked Nov 26 '13 10:11

john


1 Answers

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?

like image 112
Arne Mertz Avatar answered Sep 17 '22 14:09

Arne Mertz