Quick Links:

bal | bbl | bdl | bsl

Namespaces

Component ball_countingallocator
[Package ball]

Provide a concrete allocator that keeps count of allocated bytes. More...

Namespaces

namespace  ball

Detailed Description

Outline
Purpose:
Provide a concrete allocator that keeps count of allocated bytes.
Classes:
ball::CountingAllocator maximally-aligning, instrumented allocator adaptor
See also:
Component ball_fixedsizerecordbuffer
Description:
This component provides a special-purpose instrumented allocator, ball::CountingAllocator, that implements the bslma::Allocator protocol and guarantees maximal alignment of allocated blocks, even when the allocator supplied at construction guarantees only natural alignment (or no alignment at all). ball::CountingAllocator maintains a user-resettable running sum of the total number of bytes allocated (called byte count, see below).
   ,-----------------------.
  ( ball::CountingAllocator )
   `-----------------------'
               |         ctor/dtor
               |         numBytesTotal
               |         resetNumBytesTotal
               V
       ,----------------.
      ( bslma::Allocator )
       `----------------'
                       allocate
                       deallocate
Byte Count:
The byte count maintained by ball::CountingAllocator is set to 0 upon construction and after each call to resetNumBytesTotal. Each call of allocate(size) increases the byte count by the sum of the least multiple of bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT that is greater than or equal to size and bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT. Each call of deallocate decrements the byte count by the same amount by which the byte count was incremented on matching allocate call. The current value of the byte count is returned by the numBytesTotal accessor.
Usage:
In the following example we demonstrate how the counting allocator can be used to know the amount of dynamic memory allocated by a vector<int> after pushing one integer. Let us assume that memory for the vector comes from a bslma::Allocator named allocator.
    // First create the counting allocator using 'allocator'.
    BloombergLP::ball::CountingAllocator countingAllocator(allocator);

    // Now create the vector using the counting allocator.
    bsl::vector<int> vec(&countingAllocator);

    vec.push_back(1);
    // The following will print the memory consumed by the
    // vector and the counting allocator.
    bsl::cout << "dynamic memory after first push back: "
              << countingAllocator.numBytesTotal() << bsl::endl;