Why use array size 1 instead of pointer?

后端 未结 6 799
滥情空心
滥情空心 2020-12-02 09:04

In one C++ open source project, I see this.

struct SomeClass {
  ...
  size_t data_length;
  char data[1];
  ...
}

What are the advantages

6条回答
  •  情深已故
    2020-12-02 09:21

    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

    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 with the expected meaning because C++ has no alternative syntax to formulate these means (C99 has, it's called "flexible array member" there).

提交回复
热议问题