Aligned heap allocation for unknown types

Viewed 114

Given alignment and size of an otherwise unknown type, how can one safely construct free storage (heap) that is properly aligned?

For context: The automatic storage version is well documented. See the example at https://en.cppreference.com/w/cpp/types/aligned_storage: An opaque uninitialized storage on stack gets properly aligned, which can later be placement new'ed once type is known.

Is it possible to similarly do alignment-safe uninitialized allocation on the heap? This storage would later get placement-new initialized once the type is known (and deleted in type-aware context with proper destruction etc.)

The following naïve attempt fails: https://godbolt.org/z/PM1xWoYox

What is the mental model here with heap storage?

1 Answers

Given the problems you are having with new and delete, you might consider using aligned_alloc and free instead. For example:

#include <cstdlib>
#include <new>

struct Foo
{
    Foo (double d) : m_d (d) {}
    double m_d;
};

int main ()
{
    void *storage = aligned_alloc (alignof (Foo), sizeof (Foo));
    Foo* foo = new (storage) Foo (3.14);
    ...
    foo->~Foo ();
    free (storage);
}

Note that, to destroy an object created by placement new, you must call the destructor explicitly. You don't call delete. Then you must free the underlying storage.

Related