BDE 4.14.0 Production release
Loading...
Searching...
No Matches
bdlma_heapbypassallocator

Detailed Description

Outline

Purpose

Support memory allocation directly from virtual memory.

Classes

See also
bsls_alignmentutil

Description

The bdlma::HeapBypassAllocator class provided by this component implements a concrete allocator derived from the bslma::Allocator interface that allocates memory directly from virtual memory, bypassing the heap. Reserves virtual memory in chunks so as to grow infrequently. The chunk size can optionally be chosen by providing an argument for replenishHint in the constructor (see documentation for the constructor for advice on how to choose a good value for replenishHint). All memory allocated by this allocator is freed when the allocator's destructor is called, but not before. A natural use case is for backing large, long-lived object pools, or cases where the heap may be corrupt.

,---------------------------.
`---------------------------'
| ctor
V
,-----------------.
( bslma::Allocator )
`-----------------'
dtor
allocate
deallocate // no-op
Definition bdlma_heapbypassallocator.h:157

Usage

This section illustrates intended use of this component.

Example 1: Basic Usage

Here we allocate some memory using a heap bypass allocator, then write to that memory, then read from it and verify the values written are preserved.

{
enum {
k_LENGTH = 10 * 1000,
k_NUM_SEGMENTS = 60
};

First, we allocate some segments:

char *segments[k_NUM_SEGMENTS];
for (int i = 0; i < k_NUM_SEGMENTS; ++i) {
segments[i] = static_cast<char *>(hbpa.allocate(k_LENGTH));
BSLS_ASSERT(segments[i]);
}
void * allocate(bsls::Types::size_type size) BSLS_KEYWORD_OVERRIDE
Definition bdlma_heapbypassallocator.h:252
#define BSLS_ASSERT(X)
Definition bsls_assert.h:1804

Next, we write to the segments:

char c = 'a';
for (int i = 0; i < k_NUM_SEGMENTS; ++i) {
char *segment = segments[i];
for (int j = 0; j < k_LENGTH; ++j) {
c = (c + 1) & 0x7f;
segment[j] = c;
}
}

Finally, we read from the segments and verify the written data is still there:

c = 'a';
for (int i = 0; i < k_NUM_SEGMENTS; ++i) {
char *segment = segments[i];
for (int j = 0; j < k_LENGTH; ++j) {
c = (c + 1) & 0x7f;
BSLS_ASSERT(segment[j] == c); (void)segment;
}
}

Memory is released upon destruction of object hbpa when it goes out of scope.

}