简体   繁体   English

在C ++中的连续存储区域中存储多个结构

[英]Storing multiple structs in continuous memory area in C++

I want to store a state variable composed of multiple POD-structs of various types into a single memory area. 我想将由各种类型的多个POD结构组成的状态变量存储到单个存储区中。 Since the combination of structs used to make up the state variable is decided at run time, i cannot just place them into a surrounding struct or class. 由于用于组合状态变量的结构组合是在运行时确定的,因此我不能仅将它们放入周围的结构或类中。 Also i want the number of memory allocations to be as low as possible. 我也希望内存分配的数量尽可能少。 What is the best way to do it? 最好的方法是什么? Is the following code legal/portable or can it cause alignment errors on some platforms / with some compilers? 以下代码是否合法/可移植,或者会在某些平台上/某些编译器中导致对齐错误?

struct TestA {
    int a;
    short b;
};

struct TestB {
    int c;
    float d;
    char e;
};

int main() {
    void* mem = new uint8_t[sizeof(TestA) + sizeof(TestB)];
    TestA* a1 = (TestA*) mem;
    a1->a = a1->b = 42;
    a1++;
    TestB* b = (TestB*) a1;
    b->c = 5;
    b->d = 23.f;
    b->e = 'e';
}

What you're trying to do is essentially "placement new." 您实际上想做的是“重新放置”。 So all caveats apply here too. 因此,所有注意事项也适用于此。 If the memory location is not aligned properly for the given type, then you're into undefined behavior. 如果给定类型的内存位置未正确对齐,那么您将陷入未定义的行为。 In your code: 在您的代码中:

a1++;

is not guaranteed to give an address that's properly aligned for a TestB . 不能保证提供与TestB正确对齐的地址。 So your code is not standard-conformant. 因此,您的代码不符合标准。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM