BDE 4.14.0 Production release
|
Provide a protocol for memory allocators that support alignment.
This component provides an implementation, bdlma::AlignedAllocator
, of the base-level protocol (pure abstract interface) class, bslma::Allocator
, providing the ability to allocate raw memory with a specified alignment. The following inheritance diagram shows the classes involved and their methods:
The allocateAligned
method supplies the address of a contiguous block of allocated memory of at least the indicated size, that is aligned to a given boundary. Note that this behavior is similar to the behavior of the POSIX function posix_memalign .
This section illustrates intended use of this component.
The bdlma::AlignedAllocator
protocol provided in this component defines a bilateral contract between suppliers and consumers of raw aligned memory. In order for the bdlma::AlignedAllocator
interface to be useful, we must supply a concrete allocator that implements it.
In this example, we demonstrate how to adapt posix_memalign on Linux and AIX, memalign
on SunOS and _aligned_malloc
on Windows, to this protocol base class:
First, we specify the interface of the concrete implementation of 'MyAlignedAllocator:
Then, we implement the creators, trivially, as this class contains no instance data members.
Now, we define the virtual methods of MyAlignedAllocator
. Note that these definitions are not inline
, as they would not be inlined when invoked from the base class (the typical usage in this case):
Finally, we define a function f
that instantiates an object of type MyAlignedAllocator
:
Note that the memory is not released when the allocator goes out of scope.
In this example we illustrate how to use the bdlma::AlignedAllocator
protocol to allocate memory that is aligned to the beginning of a memory page. Third party libraries, for example device drivers that perform DMA access of device drivers, or some extreme optimizations to reduce the number of page faults, might require page aligned allocations.
First, we create an aligned allocator myAlignedAllocator
using the class MyAlignedAllocator
defined in the previous example, and obtain a bdlma::AlignedAllocator
pointer to it:
Now, assuming a page size of 4K, we allocate a buffer of 1024 bytes of memory and indicate that it should be aligned on a 4096 boundary:
Finally, we verify that the obtained address actually is aligned as expected: