I want to store a state variable composed of multiple POD-structs of various types into a single memory area. 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:
is not guaranteed to give an address that’s properly aligned for a
TestB. So your code is not standard-conformant.