单元素数组(one-element array)
In one C++ open source project, I see this.
struct SomeClass { ... size_t data_length; char data[1]; }
What are the advantages of doing so rather than using a pointer?
struct SomeClass { ... size_t data_length; char* data; }
This is a trick: variable-sized struct
With this, you don't have to allocate the memory elsewhere and make the pointer point to that.
- No extra memory management
- Accesses to the memory will hit the memory cache (much) more likely
- In addition to saving (de)allocation calls, this can also save a bit of memory as there's no space for a pointer and you could even use space that otherwise could have been struct padding.
The trick is to allocate more memory than sizeof (SomeClass), and make a SomeClass* point to it. Then the initial memory will be used by your SomeClass object, and the remaining memory can be used by the data. That is, you can say p->data[0] but also p->data[1] and so on up until you hit the end of memory you allocated.
Points can be made that this use results in undefined behavior though, because you declared your array to only have one element, but access it as if it contained more. But real compilers do allow this.
That is, instead of this:
struct SomeClass *foo = malloc(sizeof *foo); foo->data = malloc(data_len); memcpy(foo->data,data,data_len); .... free(foo->data); free(foo);
You do something like this:
struct SomeClass *foo = malloc(sizeof *foo + data_len); memcpy(foo->data,data,data_len); ... free(foo);
但是,细心的读者会发现,上面多分配了一个字节的空间,即更完美的如下:
struct SomeClass *foo = malloc(offsetof(SomeClass,data) + data_len); memcpy(foo->data,data,data_len); ... free(foo);
但是在C++中,这个技巧可能会是一个陷阱。因为:The data memeber within a single access section are guaranteed within C++ to be laid out in the order of their declaration. The layout of data contained in multiple access sections, however, is left undefined. Similarly, the layout of data members of the base and derived classes is undefined. And the presence of a virtual function also places the trick's viability in question.
浙公网安备 33010602011771号