以下是有效的C++吗?这是将扁平结构实现可变长度尾部的另一种方法.在C中,这通常使用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...
Run Code Online (Sandbox Code Playgroud)
不,它无效:
Elem 的对齐方式可能与 不同Str,因此 (reinterpret_) 转换Str+1toElem*可能会或可能不会给您一个有效的指针,并且访问可能会给出未定义的行为。
但毕竟,你为什么要做这样的事情呢?