Struct NonStandard variable length in C ++ 11?
Possible duplicate:
Technically, the behavior is undefined "struct hack>
I checked if zero-length arrays are allowed in C ++ 11. It turned out that this is not the case. From8.3.4 Arrays [dcl.array]
If the constant expression (5.19) is present, it must be an integral constant expression and its value must be greater than zero.
Since I cannot use arrays of zero length Can I use structures of variable length, being standard / chucked? For example, I would like to do something like below. How to make it well defined and standard when the buffer MAY BE EMPTY.
-edit- related: Array of zero length
struct MyStruct {
uint size;
int32 buf[0];//<-- NonStandard!
};
...
auto len=GetLength();
auto ptr=GetPtr();
auto bytelen=len*sizeof(int32);
var p = reinterpret_cast<MyStruct*>(malloc(bytelen))
p->size=len
memcpy(p->buf, ptr, bytelen)
return p;
++, C. ++, , , . :
#include <cstring>
template <typename STRUCT, typename TYPE> class flex_struct {
public:
TYPE *tail()
{
return (TYPE *) ((char *) this + padded_size());
}
// substitute malloc/free here for new[]/delete[] if you want
void *operator new(size_t size, size_t tail)
{
size_t total = padded_size() + sizeof (TYPE) * tail;
return new char[total];
}
void operator delete(void *mem)
{
delete [] (char *) mem;
}
private:
static size_t padded_size() {
size_t padded = sizeof (flex_struct<STRUCT, TYPE>);
if(padded % alignof(TYPE) != 0) {
padded = padded & ~(alignof(TYPE)-1) + alignof(TYPE);
}
return padded;
}
};
struct mystruct : public flex_struct<mystruct, char> {
int regular_member;
};
int main()
{
mystruct *s = new (100) mystruct; // mystruct with 100 chars extra
char *ptr = s->tail(); // get pointer to those 100 chars
memset(ptr, 0, 100); // fill them
delete s; // blow off struct and 100 chars
}