gpt4 book ai didi

c++ - 这是 struct hack 的 C++ 替代品吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:43:42 24 4
gpt4 key购买 nike

以下是有效的 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...

我问这个是为了回应以下 related question

最佳答案

不,它是无效的:

Elem 可能与 Str 具有不同的对齐方式,因此(重新解释_)将 Str+1 转换为 Elem* 可能会也可能不会给您一个有效的指针,并且访问可能会产生未定义的行为。

但毕竟,为什么你想要做那样的事情?

关于c++ - 这是 struct hack 的 C++ 替代品吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20214872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com