BDE 4.14.0 Production release
Loading...
Searching...
No Matches
bslma.h
Go to the documentation of this file.
1/// @file bslma.h
2///
3///
4/// @defgroup bslma Package bslma
5/// @brief Basic Standard Library Memory Allocators (bslma)
6/// @addtogroup bsl
7/// @{
8/// @addtogroup bslma
9/// [bslma]: group__bslma.html
10/// @{
11///
12/// # Purpose {#bslma-purpose}
13/// Provide allocators, guards, and other memory-management tools.
14///
15/// # Mnemonic {#bslma-mnemonic}
16/// Basic Standard Library Memory Allocators (bslma)
17///
18/// # Description {#bslma-description}
19/// The 'bslma' package provides an allocator protocol (i.e., a pure
20/// abstract interface) and a variety of concrete allocators derived from this
21/// protocol, as well as other memory-dispensing mechanisms and various guard
22/// constructs to prevent loss in case of exceptions. In addition, 'bslma' also
23/// provides a mechanism for installing a "default allocator" that will then be
24/// visible to all BDE and BDE-compliant code throughout that process. If this
25/// mechanism is not invoked explicitly, then an allocator that uses global 'new'
26/// and 'delete' is the BDE default allocator. This topic is discussed in more
27/// detail below.
28///
29/// ## Hierarchical Synopsis
30///
31/// The 'bslma' package currently has 57 components having 15 levels of physical
32/// dependency. The list below shows the hierarchical ordering of the components.
33/// The order of components within each level is not architecturally significant,
34/// just alphabetical.
35/// @code
36/// 15. bslma_managedptr
37///
38/// 14. bslma_autodeallocator
39/// bslma_destructorproctor
40///
41/// 13. bslma_deallocatorproctor !DEPRECATED!
42///
43/// 12. bslma_aatypeutil
44/// bslma_deallocatebytesproctor
45/// bslma_deallocateobjectproctor
46/// bslma_deleteobjectproctor
47///
48/// 11. bslma_aamodel
49/// bslma_allocatorutil
50/// bslma_stdallocator !DEPRECATED!
51///
52/// 10. bslma_bslallocator
53///
54/// 9. bslma_polymorphicallocator
55///
56/// 8. bslma_allocatortraits
57/// bslma_managedptr_factorydeleter !PRIVATE!
58/// bslma_managedptr_members !PRIVATE!
59/// bslma_sequentialallocator !DEPRECATED!
60/// bslma_stdtestallocator
61///
62/// 7. bslma_constructionutil
63/// bslma_sequentialpool !DEPRECATED!
64/// bslma_sharedptrinplacerep
65/// bslma_sharedptroutofplacerep
66/// bslma_testallocatormonitor
67///
68/// 6. bslma_allocatoradaptor
69/// bslma_autodestructor
70/// bslma_deallocatorguard
71/// bslma_defaultallocatorguard
72/// bslma_destructionutil
73/// bslma_destructorguard
74/// bslma_exceptionguard
75/// bslma_infrequentdeleteblocklist !DEPRECATED!
76/// bslma_managedptr_pairproxy !PRIVATE!
77/// bslma_managedptrdeleter
78/// bslma_rawdeleterguard
79/// bslma_rawdeleterproctor
80/// bslma_sharedptrrep
81///
82/// 5. bslma_default
83/// bslma_testallocator
84///
85/// 4. bslma_autorawdeleter
86/// bslma_bufferallocator !DEPRECATED!
87/// bslma_mallocfreeallocator
88/// bslma_managedallocator !DEPRECATED!
89/// bslma_newdeleteallocator
90/// bslma_testallocatorexception
91/// bslma_usesbslmaallocator
92///
93/// 3. bslma_allocator
94/// bslma_hasallocatortype
95///
96/// 2. bslma_allocatortraits_cpp03 !PRIVATE!
97/// bslma_deleterhelper
98/// bslma_isstdallocator
99/// bslma_memoryresource
100/// bslma_polymorphicallocator_cpp03 !PRIVATE!
101///
102/// 1. bslma_allocatorutil_cpp03 !PRIVATE!
103/// bslma_bslallocator_cpp03 !PRIVATE!
104/// bslma_constructionutil_cpp03 !PRIVATE!
105/// bslma_managedptr_cpp03 !PRIVATE!
106/// bslma_sharedptrinplacerep_cpp03 !PRIVATE!
107/// @endcode
108///
109/// ## Component Synopsis
110///
111/// @ref bslma_aamodel :
112/// Provide metafunctions to detect a type's allocator-awareness model.
113///
114/// @ref bslma_aatypeutil :
115/// Provide a namespace for utility functions on allocator-aware types.
116///
117/// @ref bslma_allocator :
118/// Provide a pure abstract interface for memory-allocation mechanisms.
119///
120/// @ref bslma_allocatoradaptor :
121/// Provide a polymorphic adaptor for STL-style allocators
122///
123/// @ref bslma_allocatortraits :
124/// Provide a uniform interface to standard allocator types.
125///
126/// 'bslma_allocatortraits_cpp03': !PRIVATE!
127/// Provide C++03 implementation for bslma_allocatortraits.h
128///
129/// @ref bslma_allocatorutil :
130/// Provide a namespace for utility functions on allocators.
131///
132/// 'bslma_allocatorutil_cpp03': !PRIVATE!
133/// Provide C++03 implementation for bslma_allocatorutil.h
134///
135/// @ref bslma_autodeallocator :
136/// Provide a range proctor to managed a block of memory.
137///
138/// @ref bslma_autodestructor :
139/// Provide a range proctor to manage an array of objects.
140///
141/// @ref bslma_autorawdeleter :
142/// Provide a range proctor to manage a sequence objects.
143///
144/// @ref bslma_bslallocator :
145/// Provide an STL-compatible proxy for `bslma::Allocator` objects.
146///
147/// 'bslma_bslallocator_cpp03': !PRIVATE!
148/// Provide C++03 implementation for bslma_bslallocator.h
149///
150/// @ref bslma_bufferallocator : !DEPRECATED!
151/// Support efficient memory allocations from a user-supplied buffer.
152///
153/// @ref bslma_constructionutil :
154/// Provide methods to construct arbitrarily-typed objects uniformly.
155///
156/// 'bslma_constructionutil_cpp03': !PRIVATE!
157/// Provide C++03 implementation for bslma_constructionutil.h
158///
159/// @ref bslma_deallocatebytesproctor :
160/// Provide a proctor to conditionally unwind memory block allocation.
161///
162/// @ref bslma_deallocateobjectproctor :
163/// Provide a proctor to conditionally unwind object allocation.
164///
165/// @ref bslma_deallocatorguard :
166/// Provide a guard to unconditionally manage a block of memory.
167///
168/// @ref bslma_deallocatorproctor : !DEPRECATED!
169/// Provide a proctor to conditionally manage a block memory.
170///
171/// @ref bslma_default :
172/// Provide utilities to set/fetch the default and global allocators.
173///
174/// @ref bslma_defaultallocatorguard :
175/// Provide scoped guard to temporarily change the default allocator.
176///
177/// @ref bslma_deleteobjectproctor :
178/// Provide a proctor to conditionally unwind new object creation.
179///
180/// @ref bslma_deleterhelper :
181/// Provide namespace for functions used to delete objects.
182///
183/// @ref bslma_destructionutil :
184/// Provide routines that destroy objects efficiently.
185///
186/// @ref bslma_destructorguard :
187/// Provide a guard to unconditionally manage an object.
188///
189/// @ref bslma_destructorproctor :
190/// Provide a proctor to conditionally manage an object.
191///
192/// @ref bslma_exceptionguard :
193/// Provide a check that objects throwing exceptions do not change.
194///
195/// @ref bslma_hasallocatortype :
196/// Provide a compile-time check for an @ref allocator_type typedef
197///
198/// @ref bslma_infrequentdeleteblocklist : !DEPRECATED!
199/// Provide allocation and management of a sequence of memory blocks.
200///
201/// @ref bslma_isstdallocator :
202/// Provide a compile-time check for determining allocator types.
203///
204/// @ref bslma_mallocfreeallocator :
205/// Provide malloc/free adaptor to `bslma::Allocator` protocol.
206///
207/// @ref bslma_managedallocator : !DEPRECATED!
208/// Provide a protocol for memory allocators that support `release`.
209///
210/// @ref bslma_managedptr :
211/// Provide a managed pointer class.
212///
213/// 'bslma_managedptr_cpp03': !PRIVATE!
214/// Provide C++03 implementation for bslma_managedptr.h
215///
216/// 'bslma_managedptr_factorydeleter': !PRIVATE!
217/// Provide a factory-based deleter for the managed pointer class.
218///
219/// 'bslma_managedptr_members': !PRIVATE!
220/// Provide the internal state of a managed pointer class.
221///
222/// 'bslma_managedptr_pairproxy': !PRIVATE!
223/// Provide the internal state of a managed pointer class.
224///
225/// @ref bslma_managedptrdeleter :
226/// Provide an in-core value-semantic class to call a delete function.
227///
228/// @ref bslma_memoryresource :
229/// Provide a pure abstract interface for memory-allocation mechanisms.
230///
231/// @ref bslma_newdeleteallocator :
232/// Provide singleton new/delete adaptor to `bslma::Allocator` protocol.
233///
234/// @ref bslma_polymorphicallocator :
235/// Provide an allocator interface for `bsl::memory_resource` objects.
236///
237/// 'bslma_polymorphicallocator_cpp03': !PRIVATE!
238/// Provide C++03 implementation for bslma_polymorphicallocator.h
239///
240/// @ref bslma_rawdeleterguard :
241/// Provide a guard to unconditionally manage an object.
242///
243/// @ref bslma_rawdeleterproctor :
244/// Provide a proctor to conditionally manage an object.
245///
246/// @ref bslma_sequentialallocator : !DEPRECATED!
247/// Support fast memory allocation for objects of varying sizes.
248///
249/// @ref bslma_sequentialpool : !DEPRECATED!
250/// Provide fast variable-size memory pool with allocation methods.
251///
252/// @ref bslma_sharedptrinplacerep :
253/// Provide an in-place implementation of `bslma::SharedPtrRep`.
254///
255/// 'bslma_sharedptrinplacerep_cpp03': !PRIVATE!
256/// Provide C++03 implementation for bslma_sharedptrinplacerep.h
257///
258/// @ref bslma_sharedptroutofplacerep :
259/// Provide an out-of-place implementation of `bslma::SharedPtrRep`.
260///
261/// @ref bslma_sharedptrrep :
262/// Provide an abstract class for a shared object manager.
263///
264/// @ref bslma_stdallocator : !DEPRECATED!
265/// Provide an STL-compatible proxy for `bslma::Allocator` objects.
266///
267/// @ref bslma_stdtestallocator :
268/// Provide stl-compatible, `bslma`-style allocator to track usage.
269///
270/// @ref bslma_testallocator :
271/// Provide instrumented malloc/free allocator to track memory usage.
272///
273/// @ref bslma_testallocatorexception :
274/// Provide an exception class for memory allocation operations.
275///
276/// @ref bslma_testallocatormonitor :
277/// Provide a mechanism to summarize `bslma::TestAllocator` object use.
278///
279/// @ref bslma_usesbslmaallocator :
280/// Provide a metafunction to indicate the use of `bslma` allocators.
281/// ## Component Overview
282///
283/// This section provides a brief introduction to some of the components of the
284/// 'bslma' package. See the documentation in each component for full details.
285///
286/// ### @ref bslma_allocator
287///
288/// The {@ref bslma_allocator } component defines a protocol (i.e., an abstract base
289/// class) requiring the following interface: 'allocate' for memory allocation,
290/// and 'deallocate', for allocation and deallocation of individual memory blocks.
291///
292/// ### @ref bslma_autodeallocator
293///
294/// The {@ref bslma_autodeallocator } component provides a range proctor class to
295/// manage a sequence of blocks of (otherwise-unmanaged) memory of a parameterized
296/// 'TYPE' supplied at construction. If not explicitly released, the sequence of
297/// managed memory blocks are deallocated automatically when the range proctor
298/// goes out of scope by freeing the memory using the parameterized 'ALLOCATOR'
299/// (allocator or pool) supplied at construction. This proctor mechanism is
300/// useful in guarding against memory leaks, e.g., when additional allocations may
301/// throw an exception.
302///
303/// ### @ref bslma_autodestructor
304///
305/// The {@ref bslma_autodestructor } component provides a range proctor class to
306/// manage a sequence of blocks of (otherwise-unmanaged) memory of a parameterized
307/// 'TYPE' supplied at construction. If not explicitly released, the sequence of
308/// managed memory blocks are destroyed automatically when the range proctor goes
309/// out of scope by calling each (managed) object's destructor. This proctor
310/// mechanism is useful in guarding against memory leaks, e.g., when additional
311/// allocations may throw an exception.
312///
313/// ### @ref bslma_autorawdeleter
314///
315/// The {@ref bslma_autorawdeleter } component provides a range proctor class template
316/// to manage a sequence of (otherwise-unmanaged) objects of parameterized 'TYPE'
317/// supplied at construction. If not explicitly released, the sequence of managed
318/// objects are deleted automatically when the range proctor goes out of scope by
319/// iterating over each object, first calling the (managed) object's destructor,
320/// and then freeing its memory footprint by invoking the 'deallocate' method of
321/// an allocator (or pool) of parameterized 'ALLOCATOR' type also supplied at
322/// construction. This proctor mechanism is useful in guarding against memory
323/// leaks, e.g., when additional allocations may throw an exception.
324///
325/// ### @ref bslma_deallocatorguard
326///
327/// The {@ref bslma_deallocatorguard } component provides a guard class template to
328/// *unconditionally* manage a block of (otherwise-unmanaged) memory. The managed
329/// memory is deallocated automatically when the guard object goes out of scope
330/// using the 'deallocate' method of the parameterized 'ALLOCATOR' (allocator or
331/// pool) supplied at construction. This guard mechanism is useful in ensuring
332/// that a dynamically allocated raw memory resource is safely deallocated in the
333/// presense of multiple return satements or exceptions.
334///
335/// ### @ref bslma_deallocatorproctor
336///
337/// The {@ref bslma_deallocatorproctor } component provides a proctor class template
338/// to *conditionally* manage a block of (otherwise-unmanaged) memory. If not
339/// explicitly released, the managed memory is deallocated automatically when the
340/// proctor object goes out of scope by freeing the memory using the parameterized
341/// 'ALLOCATOR' (allocator or pool) supplied at construction. This proctor
342/// mechanism is useful in guarding against memory leaks, e.g., when additional
343/// allocations may throw an exception.
344///
345/// ### @ref bslma_default
346///
347/// The {@ref bslma_default } component provides a namespace for a set of utility
348/// functions that manage the addresses of two static (global) memory allocator
349/// instances: the *default* allocator and the *global* allocator. The default
350/// allocator is the allocator used by default by all BDE components. The global
351/// allocator is the allocator used by default to construct global singleton
352/// objects. Each of these allocators are of type derived from
353/// 'bslma::Allocator'.
354///
355/// ### @ref bslma_defaultallocatorguard
356///
357/// The {@ref bslma_defaultallocatorguard } component provides a mechanism that serves
358/// as a "scoped guard" to enable the temporary replacement of the process-wide
359/// default allocator. This functionality is intended for *testing* only, and in
360/// no event should this component be used except at the very beginning of 'main'.
361///
362/// ### @ref bslma_deleterhelper
363///
364/// The {@ref bslma_deleterhelper } component provides non-primitive procedures used
365/// to delete objects of parameterized 'TYPE' by first calling the destructor of
366/// the object, and then freeing the memory footprint of the object using a
367/// parameterized 'ALLOCATOR' (allocator or pool) provided as a second argument.
368///
369/// ### @ref bslma_destructorguard
370///
371/// The {@ref bslma_destructorguard } component provides a guard class template to
372/// *unconditionally* manage an (otherwise-unmanaged) object of parameterized
373/// 'TYPE' supplied at construction. The managed object is destroyed
374/// automatically when the guard object goes out of scope by calling the (managed)
375/// object's destructor. This guard mechanism is useful in ensuring that a
376/// dynamically allocated raw memory resource is safely deallocated in the
377/// presense of multiple return satements or exceptions.
378///
379/// ### @ref bslma_destructorproctor
380///
381/// The {@ref bslma_destructorproctor } component provides a proctor class template to
382/// *conditionally* manage an (otherwise-unmanaged) object of parameterized 'TYPE'
383/// supplied at construction. If not explicitly released, the managed object is
384/// destroyed automatically when the proctor object goes out of scope by calling
385/// the object's destructor. This proctor mechanism is useful in guarding against
386/// memory leaks, e.g., when additional allocations may throw an exception.
387///
388/// ### @ref bslma_isstdallocator
389///
390///The {@ref bslma_isstdallocator } component provides a meta-function,
391///'bsl::IsStdAllocator', that determines if a type meets the requirements for an
392///allocator, as specified in [container.requirements.general].
393///
394/// ### @ref bslma_mallocfreeallocator
395///
396/// The {@ref bslma_mallocfreeallocator } component provides a wrapper around
397/// 'std::malloc' and 'std::free' that adheres to the 'bslma::Allocator' protocol
398/// (i.e., provides 'allocate' and 'deallocate' functions).
399///
400/// ### @ref bslma_newdeleteallocator
401///
402/// The {@ref bslma_newdeleteallocator } component provides a wrapper around
403/// 'operator new' and 'operator delete' that adheres to the 'bslma::Allocator'
404/// protocol (i.e., provides an 'allocate' function and a 'deallocate' function).
405///
406/// ### @ref bslma_rawdeleterguard
407///
408/// The {@ref bslma_rawdeleterguard } component provides a guard class template to
409/// *unconditionally* manage an (otherwise-unmanaged) object of parameterized
410/// 'TYPE' supplied at construction. The managed object is deleted automatically
411/// when the guard object goes out of scope by first calling the (managed)
412/// object's destructor, and then freeing the memory using the parameterized
413/// 'ALLOCATOR' (allocator or pool) also supplied at construction. This guard
414/// mechanism is useful in ensuring that a dynamically allocated raw memory
415/// resource is safely deallocated in the presense of multiple return satements or
416/// exceptions.
417///
418/// ### @ref bslma_rawdeleterproctor
419///
420/// The {@ref bslma_rawdeleterproctor } component provides a proctor class template to
421/// conditionally manage an (otherwise-unmanaged) object of parameterized 'TYPE'
422/// supplied at construction. If not explicitly released, the managed object is
423/// deleted automatically when the proctor object goes out of scope by first
424/// calling the (managed) object's destructor, and then freeing the memory using
425/// the parameterized 'ALLOCATOR' (allocator or pool) also supplied at
426/// construction. This proctor mechanism is useful in guarding against memory
427/// leaks, e.g., when additional allocations may throw an exception.
428///
429/// ### @ref bslma_testallocator
430///
431/// The {@ref bslma_testallocator } component provides an instrumented allocator that
432/// implements the 'bslma::Allocator' protocol and can be used to track various
433/// aspects of memory allocated from it. This allocator memory allocator uses
434/// global functions 'std::malloc' and 'std::free' for allocations and
435/// deallocations.
436///
437/// ### @ref bslma_testallocatorexception
438///
439/// The {@ref bslma_testallocatorexception } component defines an exception object for
440/// use in testing exceptions during memory allocations.
441///
442/// ### @ref bslma_testallocatormonitor
443///
444/// The {@ref bslma_testallocatormonitor } component provides a "monitor", a mechanism
445/// class, that allows concise tests of state change (or lack of change) in the
446/// test allocator provided at the monitor's construction.
447///
448/// ## Why Use Allocators
449///
450/// Allocators were originally introduced into STL to provide containers an
451/// abstraction for the different pointer types on the Intel architecture (such as
452/// near and far pointers). After the C++ standard (section 20.1.5 of the 1998
453/// standard) specified the requirements on an allocator type ('std::allocator')
454/// that use was rendered obsolete. But the standard also specified that all
455/// standard containers be parameterized on an allocator type that provides users
456/// greater control over the memory usage of individual objects and allows an
457/// application to control from where that memory comes (e.g., stack, heap, shared
458/// memory) and how it is distributed. By using allocators, an application can
459/// ensure efficient memory usage by reducing the number of distinct calls to
460/// global operators 'new' and 'delete' (and functions 'std::malloc' and
461/// 'std::free').
462///
463/// ## Rationale for the BDE Allocator Model
464///
465/// Although C++ standard allocators ('std::allocator') provide users great
466/// control on how containers can allocate memory having a templated allocator
467/// argument introduces other problems. Two containers instantiated with
468/// different allocator types refer to different types making interoperability
469/// between them difficult and limiting the allocator type to a per-class (as
470/// opposed to a per-instance) basis. The standard's requirement of a templated
471/// allocator type is limited to containers and does not address other
472/// user-defined types that allocate memory. Although users can augment their
473/// types to take a templated allocator type such use is likely to be tedious and
474/// to result in significant object code increase. Finally, the standard is
475/// unclear with regards to the copy semantics of stateful allocators.
476///
477/// The BDE allocator model provides a solution to these issues. BDE provides an
478/// allocator protocol and concrete allocator implementations that can be passed
479/// as constructor arguments (not as template parameters) to all objects that
480/// allocate memory. The type of an object is unaffected by the passed-in
481/// allocator and the user has full control over the scope of an allocator
482/// instance. As the model specifies a protocol it is easier to create concrete
483/// implementations and use them. The allocator model requires all elements (data
484/// members) of a container (object) to use the same allocator as the container
485/// (object). Also the allocator is not transferred on copy construction.
486///
487/// ## Allocators and Other Memory-Dispensing Mechanisms
488///
489/// An allocator is a memory manager that derives from the 'bslma::Allocator'
490/// protocol and provides an 'allocate' method for obtaining memory, and a
491/// 'deallocate' method for returning memory (to the allocator). 'bslma' also
492/// provides many memory-dispensing mechanisms that also provide an 'allocate' and
493/// a 'deallocate' method, but these memory managers are not properly referred to
494/// as "allocators", since we reserve the term "allocator" for concrete memory
495/// dispensers that actually derive from 'bslma::Allocator' and are therefore
496/// usable anywhere that a 'bslma::Allocator *' is specified. Objects that
497/// dispense memory but that are not actually "allocators" are sometimes called
498/// "end-point allocators", and may offer performance advantages to certain users.
499/// Choosing an allocation mechanisms is complex, and many factors will influence
500/// the decision. The discussions here are aimed at shedding light on this
501/// important selection process.
502///
503/// Characteristics differentiating among 'bslma' memory-allocation objects *in*
504/// *general* are:
505///
506/// * Whether or not the object isA 'bslma::Allocator'.
507///
508/// * Whether or not the allocator supports memory reuse.
509///
510/// * Whether allocation requests consume the exact amount of memory requested,
511/// an additive number of additional bytes, or a non-additive number of
512/// additional bytes (e.g., the smallest power of two that can satisfy the
513/// request).
514///
515/// * Whether allocation requests consume the exact amount of memory requested,
516///
517/// * Whether or not the allocator supports multi-threading.
518///
519/// All 'bslma' allocators are fully thread-safe but not thread-enabled (see the
520/// {@ref bsldoc_glossary } for terminology).
521///
522/// The BDE allocators have two more differentiating properties. First, whether
523/// the allocator is intended to be part of a chain (or other grouping) of
524/// allocators, or is an "end-point" allocator. The former kind support the
525/// 'bslma::Allocator' protocol. "End-point" allocators, such as a memory pool,
526/// are general-purpose mechanisms designed to minimize the runtime overhead of
527/// allocation and deallocation on a call-by-call basis and therefore do not
528/// derive from 'bslma::Allocator'. The 'bslma' package does not provide any
529/// end-point allocators although such implementations may be provided in
530/// higher-level libraries.
531///
532/// Supporting a common protocol (the 'bslma::Allocator' protocol) allows passing
533/// conformant allocators to BDE (and other) objects requiring an allocator at
534/// construction. Support of this common protocol also facilitates grouping the
535/// memory used by an object into one allocator.
536///
537/// The BDE libraries use allocators with all classes requiring dynamic memory
538/// allocation, allowing clients to fine-tune memory-related performance
539/// characteristics by replacing the established defaults with client-chosen
540/// alternatives. Because the protocol is public, clients can even write their
541/// own, customized implementations, and use those. But none of these actions are
542/// required. BDE components all work with a (preset) default allocator, and
543/// clients without special requirements need never concern themselves with
544/// allocators.
545///
546/// ## Allocator and ManagedAllocator
547///
548/// A differentiating property among 'bslma' allocators is whether the allocator
549/// is a "managed" or "unmanaged" allocator. Unmanaged allocators, concrete
550/// implementations of 'bslma::Allocator', require every allocation to be matched
551/// by a deallocation, similar to 'malloc' and 'free', or 'new' and 'delete'.
552/// Managed allocators, concrete implementations of 'bslma::ManagedAllocator', in
553/// addition to implementing the 'bslma::Allocator' protocol, provide simultaneous
554/// deallocation of all memory with one call to 'release'. This 'release'
555/// optimization can provide significant performance improvements if the only
556/// system resource held by an object (and all the objects it manages) is memory.
557/// The 'bslma' package does not provide any concrete managed allocator
558/// implementations although such implementations may be provided in higher-level
559/// libraries.
560///
561/// ## Proctors and Guards
562///
563/// The 'bslma' package contains many components for managing
564/// dynamically-allocated objects. These components can be divided along two
565/// dimensions:
566///
567/// * What their objects do on destruction: The objects of these managers can
568/// either deallocate, destroy, or delete (destroy and then deallocate) the
569/// memory or object under management.
570///
571/// * Proctors or Guards: The object managers in this package can be divided
572/// into guards and proctors. See {@ref bsldoc_glossary } for definitions of
573/// "proctor" and "guard". Proctors provide a mechanism to release the
574/// managed object, whereas, at least within 'bslma', guards do not provide a
575/// release mechanism (and so are slightly more efficient on destruction if a
576/// release mechanism isn't needed).
577///
578/// The following table categorizes the various components along these dimensions:
579///
580/// @code
581/// Deallocation Destruction Deletion
582/// +--------------------+-------------------+-------------------+
583/// Proctor | DeallocatorProctor | DestructorProctor | RawDeleterProctor |
584/// +--------------------+-------------------+-------------------+
585/// Guard | DeallocatorGuard | DestructorGuard | RawDeleterGuard |
586/// +--------------------+-------------------+-------------------+
587/// @endcode
588///
589/// Note that the components named "raw" (@ref bslma_rawdeleterproctor and
590/// @ref bslma_rawdeleterguard ) should be used only if we are sure that the supplied
591/// pointer is !not! of a type that is a secondary base class -- i.e., the
592/// (managed) object's address is (numerically) the same as when it was originally
593/// dispensed by 'ALLOCATOR'.
594///
595/// All of the object managers specified above manage an individual object or a
596/// block of memory but three components, @ref bslma_autodeallocator ,
597/// @ref bslma_autodestructor and @ref bslma_autorawdeleter allow users to manage a
598/// sequence of objects or memory blocks.
599///
600/// ## Alignment
601///
602/// Alignment of an *address* in memory refers to the relative position of that
603/// address with respect to specific (hardware-imposed) boundaries within the
604/// memory space. Any one address can be said to be on a one-byte boundary, a
605/// two-byte boundary, a four-byte boundary, or an eight-byte boundary. (Clearly,
606/// this sequence can be extended, but, as of this writing, boundaries beyond
607/// eight-byte boundaries are not relevant for these discussions on any hardware
608/// platform of interest. In particular, "alignment" as we are using the term
609/// here does not deal with page boundaries or other larger memory structures,
610/// although these considerations are important elsewhere.)
611///
612/// In general, we also speak about the alignment of (the *first* *byte* of) an
613/// entity (e.g., an 'int', a 'double', or a pointer) whose size is not
614/// necessarily one byte. As a practical matter, for each entity separately, some
615/// alignments are "safe" and some are not. By "not safe" we mean that, for most
616/// platforms (e.g., all of our Unix machines), attempting to access an entity at
617/// an address that is not safely aligned for that entity will cause a bus error,
618/// crashing the program on the spot. In the very best case, the access will
619/// incur a performance penalty as the memory is shifted appropriately between its
620/// initial address and its target address (e.g., a register).
621///
622/// The BDE memory managers provide three kinds of alignment: NATURAL, MAXIMAL,
623/// and BYTE -- but note that BYTE alignment is also referred to as "no alignment"
624/// or "none" in this document, since every address is aligned to *some* byte.
625///
626/// A C/C++ variable is "naturally aligned" if its size divides the numerical
627/// value of its address. An address is "maximally aligned" if it can serve as a
628/// naturally-aligned address no matter what type of object might be stored there.
629/// That is, it meets the alignment requirements of the type with the maximally
630/// restrictive needs.
631///
632/// Accessing data stored at an aligned address is *faster* on Intel platforms and
633/// *required* on almost all Unix platforms. Reading (or writing) a C/C++
634/// variable at an unaligned address will cause a Bus Error on these Unix
635/// platforms, and thus crash the program.
636///
637/// Normally, programmers need not worry about alignment for dynamically allocated
638/// memory. The runtime system's 'new' (or 'malloc', for C) automatically return
639/// memory blocks beginning at maximally-aligned addresses (the C++ standard
640/// requires it of 'new'). All memory managers in the 'bslma' package return
641/// maximally-aligned memory.
642///
643/// The cost of obtaining aligned addresses is twofold: an increase in the memory
644/// used (allocators returning aligned addresses do so by skipping bytes that
645/// could otherwise be used, so as to return an appropriate address), and
646/// additional computation time to calculate the needed alignment and subsequent
647/// offset.
648///
649/// See the {@ref bsls_alignment |Alignment Strategy} component for further
650/// information on the supported alignment strategies.
651///
652/// ## Deallocation
653///
654/// Some managers may not deallocate individual items. (The 'deallocate' function
655/// is almost always provided, but in these managers it performs no action.) Such
656/// managers provide a 'release' function instead, which relinquishes *all* memory
657/// allocated by that manager since the previous 'release' call. All memory
658/// managers in the 'bslma' package deallocate the specified memory during a
659/// 'deallocate' method invocation.
660///
661/// ## Type and Origination
662///
663/// Most managers provide variable-sized, untyped (i.e., 'void *') memory.
664///
665/// Different components manage memory in different ways, but they necessarily
666/// *obtain* the memory that they manage from one of the two usual sources: the
667/// heap or the stack. The 'bslma::NewDeleteAllocator' is hard-coded to obtain
668/// memory from the heap -- its underlying source is 'operator new'.
669///
670/// The managers in the 'bslma' package are compared in the following tables:
671/// @code
672/// PERFORMANCE CHARACTERISTICS
673///
674/// Memory Source Allocation Alignment Out-of-memory
675/// Cost OVER Handling
676/// Underlying
677/// Source
678/// +-----------------+--------------+---------+--------------------+
679/// NewDelete | 'operator new' | 0 if inlined,|MAXIMAL | Return value 0 |
680/// Allocator | |else vfn call+| | |
681/// +-----------------+--------------+---------+--------------------+
682/// MallocFree | 'std::malloc' | 0 if inlined,|MAXIMAL | Return value 0 |
683/// Allocator | |else vfn call+| | |
684/// +-----------------+--------------+---------+--------------------+
685/// Test | 'malloc' | N/A | None | Return value 0 |
686/// Allocator | | | | |
687/// +-----------------+--------------+---------+--------------------+
688///
689/// SEMANTICS
690///
691/// Deallocation Storage Facility
692/// +-----------------------+-------------------------+
693/// Newdelete | Single items only | Untyped, varying sizes |
694/// Allocator | | |
695/// +-----------------------+-------------------------+
696/// MallocFree | Single items only | Untyped, varying sizes |
697/// Allocator | | |
698/// +-----------------------+-------------------------+
699/// Test | Single items only | Untyped, varying sizes |
700/// Allocator | | |
701/// +-----------------------+-------------------------+
702/// @endcode
703///
704/// ## The Default Allocator
705///
706/// All object types in BDE libraries needing dynamic memory require that an
707/// allocator be passed to their constructor. They take a 'bslma::Allocator *'
708/// argument, which defaults to the value of 'bslma::Default::defaultAllocator()'.
709/// This value is set by BDE library code to be
710/// 'bslma::NewDeleteAllocator::singleton()', but it can be changed:
711/// 'bslma::Default::setDefaultAllocator' sets the value of the (global) default
712/// allocator (although this is *strongly* discouraged), and
713/// 'bslma::Default::allocator' returns it.
714///
715/// ## Interaction With Other Packages
716///
717/// All BDE library objects needing dynamic memory require that an allocator be
718/// passed to their constructor, which defaults to the allocator currently
719/// installed as the default allocator.
720///
721/// ## Usage
722///
723/// This section illustrates intended use of components in this package.
724///
725/// ### Example 1: Creating a type that uses bslma::Allocator
726///
727/// If objects of a class allocate memory (or contain data members that do) then
728/// having all constructors of that class accept the address of a
729/// 'bslma::Allocator' object as an argument allows its clients to control how
730/// those objects allocate memory. An example of this is provided by showing the
731/// creators of a 'Customer' 'class' that stores the first and last names of a
732/// customer as 'bsl::string' objects and the various account numbers of that
733/// customer using a 'bsl::vector'. For simplicity part of the interface is
734/// elided.
735/// @code
736/// // ==============
737/// // class Customer
738/// // ==============
739///
740/// class Customer {
741/// // This simply constrained (value-semantic) attribute class represents
742/// // the information about a bank's customer. A customer's first and last
743/// // name are represented as 'bsl::string' objects, the associated accounts
744/// // are stored in a 'bsl::vector<int>', and the employee identification
745/// // number is represented by an 'int'. Note that the class invariants are
746/// // identically the constraints on the individual attributes.
747/// //
748/// // This class:
749/// // * supports a complete set of *value-semantic* operations
750/// // * except for 'bslx' serialization
751/// // * is *exception-neutral* (agnostic)
752/// // * is *alias-safe*
753/// // * is 'const' *thread-safe*
754///
755/// // DATA
756/// bsl::string d_firstName; // first name
757/// bsl::string d_lastName; // last name
758/// bsl::vector<int> d_accounts; // account numbers
759/// int d_id; // customer identification number
760///
761/// public:
762/// @endcode
763/// Note that the constructor declarations below all accept the address of a
764/// 'bslma::Allocator' argument.
765/// @code
766/// // CREATORS
767/// Customer(bslma::Allocator *basicAllocator = 0);
768/// // Create a 'Customer' object having the (default) attribute values:
769/// //..
770/// // firstName() == ""
771/// // lastName() == ""
772/// // accounts() == 0
773/// // id() == 0
774/// //..
775/// // Optionally specify a 'basicAllocator' used to supply memory. If
776/// // 'basicAllocator' is 0, the currently installed default allocator
777/// // is used.
778///
779/// Customer(const bslstl::StringRef& firstName,
780/// const bslstl::StringRef& lastName,
781/// const bsl::vector<int>& accounts,
782/// int id,
783/// bslma::Allocator *basicAllocator = 0);
784/// // Create a 'Customer' object having the specified 'firstName',
785/// // 'lastName', 'accounts', and 'id'' attribute values. Optionally
786/// // specify a 'basicAllocator' used to supply memory. If
787/// // 'basicAllocator' is 0, the currently installed default allocator
788/// // is used.
789///
790/// Customer(const Customer& original, bslma::Allocator *basicAllocator = 0);
791/// // Create a 'Customer' object having the same value as the specified
792/// // 'original' object. Optionally specify a 'basicAllocator' used to
793/// // supply memory. If 'basicAllocator' is 0, the currently installed
794/// // default allocator is used.
795///
796/// //! ~Customer() = default;
797/// // Destroy this object.
798///
799/// // Aspects
800///
801/// bslma::Allocator *allocator() const;
802/// // Return the allocator used by this object to supply memory. Note
803/// // that if no allocator was supplied at construction the currently
804/// // installed default allocator is used.
805///
806/// ...
807/// };
808/// @endcode
809/// Since the 'Customer' 'class' contains members that allocate memory it can
810/// associate the 'UsesBslmaAllocator' trait defined in the 'bslma' package to
811/// programmatically inform templated code that it uses an allocator.
812/// @code
813///
814/// // TRAITS
815/// namespace BloombergLP{
816/// namespace bslma {
817///
818/// template <> struct UsesBslmaAllocator<Customer> : bsl::true_type {};
819///
820/// }
821/// }
822///
823/// // ==========================================================================
824/// // INLINE FUNCTION DEFINITIONS
825/// // ==========================================================================
826///
827/// // --------------
828/// // class Customer
829/// // --------------
830///
831/// @endcode
832/// The constructor implementations of 'Customer' can simply forward the
833/// basicAllocator argument to its data members. All BSL containers, including
834/// 'bsl::string' and 'bsl::vector', accept a 'bslma::Allocator' constructor
835/// argument:
836/// @code
837///
838/// // CREATORS
839/// inline
840/// Customer::Customer(bslma::Allocator *basicAllocator)
841/// : d_firstName(basicAllocator)
842/// , d_lastName(basicAllocator)
843/// , d_accounts(basicAllocator)
844/// , d_id(0)
845/// {
846/// }
847///
848/// inline
849/// Customer::Customer(const bslstl::StringRef& firstName,
850/// const bslstl::StringRef& lastName,
851/// const bsl::vector<int>& accounts,
852/// int id,
853/// bslma::Allocator *basicAllocator)
854/// : d_firstName(firstName.begin(), firstName.end(), basicAllocator)
855/// , d_lastName(lastName.begin(), lastName.end(), basicAllocator)
856/// , d_accounts(accounts, basicAllocator)
857/// , d_id(id)
858/// {
859/// BSLS_ASSERT_SAFE(!firstName.isEmpty());
860/// BSLS_ASSERT_SAFE(!lastName.isEmpty());
861/// }
862///
863/// inline
864/// Customer::Customer(const Customer& original,
865/// bslma::Allocator *basicAllocator)
866/// : d_firstName(original.d_firstName, basicAllocator)
867/// , d_lastName(original.d_lastName, basicAllocator)
868/// , d_accounts(original.d_accounts, basicAllocator)
869/// , d_id(original.d_id)
870/// {
871/// }
872///
873/// // MANIPULATORS
874/// inline
875/// Customer& Customer::operator=(const Customer& rhs)
876/// {
877/// d_firstName = rhs.d_firstName;
878/// d_lastName = rhs.d_lastName;
879/// d_accounts = rhs.d_accounts;
880/// d_id = rhs.d_id;
881/// return *this;
882/// }
883///
884/// // Aspects
885///
886/// inline
887/// bslma::Allocator *Customer::allocator() const
888/// {
889/// return d_firstName.get_allocator().mechanism();
890/// }
891///
892/// @endcode
893/// Again for simplicity the rest of the implementation is not provided.
894///
895/// ### Example 2: Implementing Templates That May Be Supplied Allocating Types
896///
897/// When writing templatized code that may be parameterized on types that allocate
898/// memory it is often necessary to decide whether to pass through the
899/// user-supplied allocator to individual objects. Such code (and containers) can
900/// use the UsesBslmaAllocator trait defined in the bslma package to decide
901/// whether to pass the allocator to an object's constructor. An example of using
902/// this trait is provided below by showing a simplified parameterized object pool
903/// 'class':
904///
905/// @code
906/// // ================
907/// // class ObjectPool
908/// // ================
909///
910/// template <typename TYPE>
911/// class ObjectPool {
912/// // This 'class' provides a pool of reusable objects of the parameterized
913/// // 'TYPE' and assumes that the parameterized 'TYPE' provides a default
914/// // constructor, a destructor, and a 'reset' method.
915///
916/// // DATA
917/// bsl::list<TYPE *> d_objects; // list of managed objects
918/// bslma::Allocator *d_allocator_p; // memory allocator (held, not owned)
919///
920/// // PRIVATE CLASS METHODS
921/// TYPE *createObject(bsl::false_type);
922/// // Construct an object of the specified 'TYPE' that *does not*
923/// // require an allocator to be passed to its constructor.
924///
925/// TYPE *createObject(bsl::true_type);
926/// // Construct an object of the specified 'TYPE' that *requires* an
927/// // allocator to be passed to its constructor.
928///
929/// public:
930/// // CREATORS
931/// ObjectPool(bslma::Allocator *basicAllocator = 0);
932/// // Create an object pool that invokes the default constructor of the
933/// // parameterized 'TYPE' to construct objects. The optionally
934/// // specified 'basicAllocator' is used to supply memory. If
935/// // 'basicAllocator' is 0, the currently installed default allocator
936/// // is used.
937///
938/// ~ObjectPool();
939/// // Destroy this object pool. All objects created by this pool are
940/// // destroyed (even if some of them are still in use) and memory is
941/// // reclaimed.
942///
943/// // MANIPULATORS
944/// TYPE* getObject();
945/// // Return an address providing modifiable access to a
946/// // default-constructed object of the parameterized 'TYPE'. If this
947/// // pool does not have any free objects then a default-constructed
948/// // object is allocated and returned.
949///
950/// void releaseObject(TYPE *object);
951/// // Return the specified 'object' back to this object pool. Invoke
952/// // the 'reset' method on 'object'.
953///
954/// // The rest of the interface is elided for brevity.
955/// };
956///
957/// // ==========================================================================
958/// // INLINE FUNCTION DEFINITIONS
959/// // ==========================================================================
960///
961/// // ----------------
962/// // class ObjectPool
963/// // ----------------
964///
965/// @endcode
966/// The 'createObject' private methods below allow an object to be created by
967/// specifying an allocator only if it has the 'UsesBslmaAllocator' trait.
968/// @code
969///
970/// // PRIVATE CLASS METHODS
971/// template <typename TYPE>
972/// inline
973/// TYPE *ObjectPool<TYPE>::createObject(bsl::false_type)
974/// {
975/// return new (*d_allocator_p) TYPE();
976/// }
977///
978/// template <typename TYPE>
979/// inline
980/// TYPE *ObjectPool<TYPE>::createObject(bsl::true_type)
981/// {
982/// return new (*d_allocator_p) TYPE(d_allocator_p);
983/// }
984///
985/// // CREATORS
986/// template <typename TYPE>
987/// inline
988/// ObjectPool<TYPE>::ObjectPool(bslma::Allocator *basicAllocator)
989/// : d_objects(basicAllocator)
990/// , d_allocator_p(bslma::Default::allocator(basicAllocator))
991/// {
992/// }
993///
994/// template <typename TYPE>
995/// ObjectPool<TYPE>::~ObjectPool()
996/// {
997/// for (bsl::list<TYPE *>::iterator iter = d_objects.begin();
998/// iter != d_objects.end();
999/// ++iter) {
1000/// d_allocator_p->deleteObject(*iter);
1001/// }
1002/// d_objects.clear();
1003/// }
1004///
1005/// // MANIPULATORS
1006/// template <typename TYPE>
1007/// TYPE *ObjectPool<TYPE>::getObject()
1008/// {
1009/// if (d_objects.size()) {
1010/// TYPE *object = d_objects.back();
1011/// d_objects.pop_back();
1012/// return object; // RETURN
1013/// }
1014///
1015/// return createObject(bslma::UsesBslmaAllocator<TYPE>());
1016/// }
1017///
1018/// template <typename TYPE>
1019/// inline
1020/// void ObjectPool<TYPE>::releaseObject(TYPE *object)
1021/// {
1022/// object->reset();
1023/// d_objects.push_back(object);
1024/// }
1025/// @endcode
1026///
1027/// ### Example 3: Implementing a Customized Allocator
1028///
1029/// Since 'bslma::Allocator' is a protocol, users can create their own concrete
1030/// implementations for object-specific situations. A complete example of a
1031/// concrete implementation that allocates memory from a user-supplied static
1032/// buffer and reverts to an allocator specified at construction if that buffer is
1033/// exhausted is provided below:
1034///
1035/// @code
1036/// // =====================
1037/// // class BufferAllocator
1038/// // =====================
1039///
1040/// using namespace BloombergLP;
1041///
1042/// class BufferAllocator : public bslma::Allocator {
1043/// // This 'class' provides a concrete buffer allocator that implements the
1044/// // 'bslma::Allocator' interface, allocating memory blocks from a
1045/// // fixed-size buffer that is supplied by the user at construction, or
1046/// // from an optionally-specified allocator once that buffer is exhausted.
1047///
1048/// // DATA
1049/// char *d_buffer_p; // buffer to use for memory
1050/// // allocations (held, not owned)
1051/// int d_bufferSize; // initial buffer size
1052/// int d_cursor; // current cursor
1053/// bslma::Allocator *d_allocator_p; // memory allocator to use once
1054/// // 'd_buffer_p' is exhausted (held,
1055/// // not owned)
1056///
1057/// // NOT IMPLEMENTED
1058/// BufferAllocator(const BufferAllocator&);
1059/// BufferAllocator& operator=(const BufferAllocator&);
1060///
1061/// public:
1062/// // CREATORS
1063/// BufferAllocator(char *buffer,
1064/// int bufferSize,
1065/// bslma::Allocator *basicAllocator = 0);
1066/// // Create a buffer allocator for allocating memory blocks from the
1067/// // specified 'buffer' of the specified 'bufferSize'. Optionally
1068/// // specify a 'basicAllocator' used to supply memory after that
1069/// // 'buffer' is exhausted. If 'basicAllocator' is 0, the currently
1070/// // installed default allocator is used.
1071///
1072/// virtual ~BufferAllocator();
1073/// // Destroy this buffer allocator.
1074///
1075/// // MANIPULATORS
1076/// virtual void *allocate(bsls::Types::size_type size);
1077/// // Return the address of a contiguous block of maximally-aligned
1078/// // memory of the specified 'size' (in bytes). If 'size' is 0 no
1079/// // memory is allocated and 0 is returned. If the allocation request
1080/// // exceeds the remaining free memory space in the external buffer
1081/// // supplied at construction, the allocator specified at construction
1082/// // is used. The behavior is undefined unless '0 <= size'.
1083///
1084/// virtual void deallocate(void *address);
1085/// // Deallocate the specified 'address' if it did not come from the
1086/// // external buffer specified at construction and do nothing
1087/// // otherwise. Note that if the buffer specified at construction was
1088/// // not exhausted then no deallocation overhead is incurred.
1089/// };
1090///
1091/// // ==========================================================================
1092/// // INLINE FUNCTION DEFINITIONS
1093/// // ==========================================================================
1094///
1095/// // ---------------------
1096/// // class BufferAllocator
1097/// // ---------------------
1098///
1099/// // CREATORS
1100/// inline
1101/// BufferAllocator::BufferAllocator(char *buffer,
1102/// int bufferSize,
1103/// bslma::Allocator *basicAllocator)
1104/// : d_buffer_p(buffer)
1105/// , d_bufferSize(bufferSize)
1106/// , d_cursor(0)
1107/// , d_allocator_p(bslma::Default::allocator(basicAllocator))
1108/// {
1109/// }
1110///
1111/// inline
1112/// BufferAllocator::~BufferAllocator()
1113/// {
1114/// }
1115///
1116/// @endcode
1117/// The function definitions for the 'BufferAllocator' 'class' are provided below:
1118/// @code
1119/// // MANIPULATORS
1120/// void *BufferAllocator::allocate(bsls::Types::size_type size)
1121/// {
1122/// BSLS_ASSERT_SAFE(0 <= size);
1123///
1124/// // Calculate the appropriate aligned offset
1125///
1126/// const int offset = bsls::AlignmentUtil::calculateAlignmentOffset(
1127/// d_buffer_p + d_cursor,
1128/// bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT);
1129///
1130/// if (d_cursor + offset + size > d_bufferSize) {
1131/// return d_allocator_p->allocate(size); // RETURN
1132/// }
1133///
1134/// void *result = static_cast<void *>(&d_buffer_p[d_cursor + offset]);
1135/// d_cursor += offset + size;
1136///
1137/// return result;
1138/// }
1139///
1140/// void BufferAllocator::deallocate(void *address)
1141/// {
1142/// if (!(d_buffer_p <= address && address < d_buffer_p + d_bufferSize)) {
1143/// d_allocator_p->deallocate(address);
1144/// }
1145/// }
1146/// @endcode
1147///
1148/// @}
1149/** @} */