C ++ 11中的可变长度结构非标准? [英] Variable length Struct NonStandard in C++11?
问题描述
可能重复:
是struct hack技术上未定义的行为?
我检查了如果零长度数组允许在C + +11。它似乎他们不是。从 8.3.4数组[dcl.array]
I checked if zero length arrays were allowed in C++11. It appeared they aren't. From 8.3.4 Arrays [dcl.array]
(5.19),它将是一个整数常数表达式,其值应大于零。
If the constant-expression (5.19) is present, it shall be an integral constant expression and its value shall be greater than zero.
length arrays是否可以使用可变长度结构,同时是标准/井定义?例如,我想要做类似下面的事情。
Since i cant use zero length arrays Is it possible to use variable length structs while being standard/Well Defined? For example I'd want to do something like the below. How do I make it well defined and standard when the buffer MAY BE EMPTY.
-edit-相关:零长度数组
-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 ++,需要这个灵活的数组成员Hack在C + +,因为你可以很容易地使一个模板类,可以赋予任何结构与一个灵活的数组超过结束和封装指针运算计算和内存分配,使其工作。观看:
This is C++, not C. You don't need this flexible array member hack in C++, because you can easily make a template class which can endow any struct with a flexible array past the end and encapsulate the pointer arithmetic calculation and the memory allocation to make it work. Watch:
#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
}
这篇关于C ++ 11中的可变长度结构非标准?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!