|
BDE 4.39.x Production Release
|
Provide support for implementing memory resources.
Provide support for implementing memory resources
This component provides support functions and types for implementing a class derived from bsl::memory_resource. Currently, it provides a utility function, singularPointer, that provides a pointer suitable for an allocate function to return when a zero-sized allocation is requested.
This section illustrates intended use of this component.
In this example, we derive a NewDeleteResource class, derived from bsl::memory_resource, that allocates and deallocate using operator new and operator delete, respectively, and uses singularPointer() as a special value when allocating and allocating zero bytes.
First, we define the class interface, which implements the protected virtual functions do_allocate, do_deallocate, and do_is_equal:
Next, we implement the do_allocate method, which forwards most requests to operator new. Section [basic.stc.dynamic.allocation] of the C++ standard, however states that the return value of an allocation function when the requested size is zero is a non-null pointer to a suitably aligned block of storage, so we use singularPointer to provide the address in such circumstances:
Next, we implement the do_deallocate method, which forwards most requests to operator delete, but does nothing if the incoming pointer was the result of a zero-sized allocation:
Next, we complete the implementation with do_is_equal. All instances of NewDeleteResource compare equal, so we need only check that the argument is a NewDeleteResource. As a short-cut, we check if the address of b is the same as this, to quickly catch the common case that they are both pointers to the singleton object:
Now, when we call allocate, we observe that each non-zero allocation yields a different pointer, whereas all of the zero allocations yield the same address.
Finally, when we deallocate memory, we would expect nothing to happen when deallocating the zero-sized blocks p3 and p4: