When I call posix_memalign
to allocate aligned memory for an object of type Foo
in my C++ code, I am required to do a reinterpret_cast
of the address of that pointer to void**
.
In general when I encounter this situation, it implies that I am missing some language feature. That is, it feels like I am calling malloc
in c++
when I should be calling new
.
,
Is there a type-aware new
equivalent for aligned memory allocation in c++
?
Actually, you don't want to do a
reinterpret_cast
because then yourFoo
constructor isn't called. If you need to allocate memory from a special place, you then call placement new to construct the object in that memory:The only other way (pre C++11) would be overriding the
new
operator for your class. That works if you have a particular class that always requires this special allocation:Then anytime you call
new Foo()
it will invoke this allocator. See http://en.cppreference.com/w/cpp/memory/new/operator_new for more information. Overridingoperator new
andoperator delete
can be done for individual classes or globally.C++11 has added native language support for alignment declarations and aligned allocation.
You can specify
alignas(N)
on your type in C++11 to specify the minimum alignment for new objects, which the defaultnew
will respect.Example from cppreference:
then you can simply do
For a replacement for
posix_memalign
, you can usestd::aligned_storage<sizeof(T), N>
, also in C++11.I will start with the core advice first.
then when you are done with the
Foo* foo
, do afoo->~Foo(); free(foo);
instead ofdelete
.Note the lack of
reinterpret_cast
s.Here is an attempt to make it generic:
The
unique_ptr
aliasaligned_ptr
bundles the destroyer along with the pointer -- as this data requires destruction and free, not delete, this makes it clear. You can still.release()
the pointer out, but you still have to do the steps.