I have a collection of opaque objects and related functions API. Such objects are typically created on the heap, but that involves a non-trivial amount of overhead. And when aggregate together, that adds layers upon layers of extra pointers and indirection.
I would like to be able to compose multiples of those opaque types in structures or as stack objects in order to eliminate the heap memory overhead.
I do know the sizes and alignments of those opaque types, so what would be the optimal way to present that information to the compiler?
I am thinking fixed size byte arrays with explicit alignment. Just wanted to check for a second opinion on whether this is the way to go, and for any potential pitfalls.
Edit: hopefully this clarifies my intent:
struct aggregateHeap {
OpaqueType1 * op1;
OpaqueType2 * op2;
OpaqueType3 * op3;
}; // 3 extra pointers + heap allocation + additional indirection level overhead
struct aggregateStack {
AlignedBlob(OpaqueType1Size, OpaqueType1Align) op1;
AlignedBlob(OpaqueType2Size, OpaqueType2Align) op2;
AlignedBlob(OpaqueType3Size, OpaqueType3Align) op3;
}; // no overhead
void fooHeap() {
OpaqueType1 * op1 = createOpaqueType1();
OpaqueType2 * op2 = createOpaqueType2();
OpaqueType3 * op3 = createOpaqueType3();
// use opaque objects with api
} // heap allocation in critical section
void fooStack() {
AlignedBlob(OpaqueType1Size, OpaqueType1Align) op1;
AlignedBlob(OpaqueType2Size, OpaqueType2Align) op2;
AlignedBlob(OpaqueType3Size, OpaqueType3Align) op3;
createOpaqueType1(op1);
createOpaqueType2(op2);
createOpaqueType3(op3);
// use opaque objects with api
} // no allocation overhead
void fooAggregateStack() {
struct aggregateStack agg;
InitAggregate(&agg);
// use agg
} // no overhead, much cleaner