Home > Mobile >  C 20 pre-allocate array to store multiple types
C 20 pre-allocate array to store multiple types

Time:05-17

I have a Linux code.

I would like to pre-allocate 10000 items of different types as circular array. I always know which object type it is.

Since biggest object takes 54 bytes - I want to allocate 10000 x 54 chunk of memory.

Whats the correct pointer arithmetic to retrieve reference to an object with index i ?

x64 architecture

uint8_t cache[10000 * 54];

MyType* o = static_cast<MyType*>(cache   i * 54);
o.Prop1 = 10;

is this right?

EDIT: I need most efficient solution

EDIT2: these are instances of classes not structs (if that makes difference for aligning)

CodePudding user response:

Use std::array<std::variant<Type1, Type2, Type3, ...>, 100000> cache;

CodePudding user response:

The pointer arithmetic is correct, however be very careful about those structure sizes. Unless you prevent padding (with like #pragma pack, for example), the compiler could easily throw a curve ball your way.

Also because your allocation is unaligned, you will be paying a moderate performance tax on every access inside that structure. If memory isn't an issue, you should 64-bit align your objects.

  • Related