13.36 <memory>The <memory> header declares function and class templates for allocating and using memory, such as the auto_ptr<> smart pointer, algorithms for working with uninitialized memory, and a standard allocator for use with the standard containers. The auto_ptr class template provides a simple ownership model for working with pointers. It can be extremely useful for writing exception-safe code. On the other hand, copying an auto_ptr<> object does not produce an exact copy (ownership of the pointer is transferred), so auto_ptr<> objects cannot be stored in standard containers. Several functions work with uninitialized memory, which can be helpful when implementing a container. For example, an implementation of vector must allocate an uninitialized array of objects and initialize elements of the array as they are needed. The uninitialized_ . . . functions can come in handy for that purpose. The allocator class template manages memory allocation and deallocation and the construction and destruction of objects in the memory it manages. It is the default allocator for all the standard containers.
The allocator class template encapsulates basic allocation and deallocation functions. The standard containers rely on allocators for memory management and use allocator as the default allocator. Most programmers do not need to use allocator, which offers few advantages over plain new and delete. However, if you want to write your own container, or provide a custom allocator for the standard containers, you should take the time to understand allocator. Perhaps the easiest way to understand allocator is to take a look at a trivial implementation in Example 13-30. Note that a library might have a more complicated implementation to handle multithreading, improve performance, etc. Some libraries offer allocators for special purposes, such as allocating memory that can be shared among multiple processes. This particular implementation is just a sample. ExampleExample 13-30. Sample allocator implementationtemplate<typename T> class myallocator { public: typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; template <class U> struct rebind { typedef myallocator<U> other; }; myallocator( ) throw( ) {} myallocator(const myallocator&) throw( ) {} template <class U> myallocator(const myallocator<U>&) throw( ) {} ~myallocator( ) throw( ) {} pointer address(reference x) const {return &x;} const_pointer address(const_reference x) const {return &x;} pointer allocate(size_type n, void* hint = 0) { return static_cast<T*>(::operator new (n * sizeof(T)) ); } void deallocate(pointer p, size_type n) { ::operator delete(static_cast<void*>(p)); } size_type max_size( ) const throw( ) { return std::numeric_limits<size_type>::max( ) / sizeof(T); } void construct(pointer p, const T& val) { new(static_cast<void*>(p)) T(val); } void destroy(pointer p) { p->~T( ); } }; template<typename T> bool operator==(const myallocator<T>&, const myallocator<T>&) { return true; } template<typename T> bool operator!=(const myallocator<T>&, const myallocator<T>&) { return false; } template<> class myallocator<void> { public: typedef void* pointer; typedef const void* const_pointer; typedef void value_type; template <class U> struct rebind { typedef myallocator<U> other; }; }; The following are the members of allocator:
See Alsoallocator<void> class, <new>, new operator, delete operator
The allocator<void> specialization is necessary to represent pointers to void without permitting the allocation of objects of type void. See Alsoallocator class template
The auto_ptr class template implements a smart pointer to manage ownership of pointers. Proper use of auto_ptr ensures that a pointer has exactly one owner (which prevents accidental double deletes), and the owner automatically frees the memory when the owner goes out of scope (which prevents memory leaks). Assignment of auto_ptr values transfers ownership from the source to the target of the assignment. The auto_ptr_ref type holds a reference to an auto_ptr. Implicit conversions between auto_ptr and auto_ptr_ref facilitate the return of auto_ptr objects from functions. Usually, you can ignore the auto_ptr_ref type and let the implicit conversions handle the details for you. All you need to do is use auto_ptr as a return type. The details of auto_ptr_ref are implementation-defined. Some of the typical uses for auto_ptr are:
Because you cannot simply copy or assign an auto_ptr, you cannot use auto_ptr objects in a standard container. Another limitation is that auto_ptr cannot hold a pointer to an array. Allocating and freeing a single object (e.g., new int) is different from allocating and freeing an array of objects, (e.g., new int[42]), and auto_ptr is designed to work only with single objects.
The Boost project has additional smart-pointer class templates that permit copying, arrays, and shared ownership. See Appendix B for more information about Boost. Example 13-31 shows some uses of auto_ptr. ExampleExample 13-31. Sample uses of auto_ptrclass brush { . . . }; class pen { . . . }; // A function can return an auto_ptr<> object. std::auto_ptr<brush> default_brush( ) { return std::auto_ptr<brush>(new brush); } class DisplayContext { // Display or graphics context for drawing on a window. public: DisplayContext( ) : brush_(default_brush( )), pen_(new pen) {...} . . . private: // Make sure caller never tries to copy or assign // DisplayContext, but uses only objects that are // managed by auto_ptr<>. DisplayContext(const DisplayContext& dc); DisplayContext& operator=(const DisplayContext& dc); // Automatically manage lifetime of the pen and brush. // When the DisplayContext is freed, so are the pen // and brush instances. std::auto_ptr<brush> brush_; std::auto_ptr<pen> pen_; }; void repaint( ) { // Allocate a new display context. Use auto_ptr to ensure // that it will be freed automatically. std::auto_ptr<DisplayContext> dc(new DisplayContext( )); // Draw stuff on the display context. dc->draw( . . . ); // No need to call release; the display context is // automatically released when repaint( ) returns. } int main( ) { std::auto_ptr<DisplayContext> dc1(new DisplayContext); std::auto_ptr<DisplayContext> dc2(dc1); dc1 = dc2; repaint( ); } The following are the members of auto_ptr:
See Alsonew operator
The get_temporary_buffer function template allocates memory for temporary use. The request is for up to n adjacent objects of type T. The return value is a pair of the pointer to the newly allocated memory and the actual size of the memory allocated (in units of sizeof(T)). If the memory cannot be allocated, the return value is a pair of 0s. The allocated memory must be freed by calling return_temporary_buffer. The temporary buffer is uninitialized. This function has limited usefulness. You must test the return value to see how much memory was allocated and ensure that the memory is properly freed if an exception is thrown. It is usually simpler to call new and save the pointer in an auto_ptr<>. See Alsoauto_ptr class template, return_temporary_buffer function template, pair in <utility>
The operator== function template always returns true. In other words, any object of type allocator is considered to be the same as every other allocator. See Alsoallocator class template
The operator!= function template always returns false. In other words, any object of type allocator is considered to be the same as every other allocator. See Alsoallocator class template
The raw_storage_iterator class template implements an output iterator that writes to uninitialized memory. It adapts another output iterator that must have operator& return a pointer to T. The adapted iterator is typically used as a pointer to uninitialized memory. Use the raw_storage_iterator as you would any other output iterator. See Alsouninitialized_copy function template, uninitialized_fill function template, uninitialized_fill_n function template, <iterator>
The return_temporary_buffer function reclaims the memory that was previously allocated by get_temporary_buffer. See Alsoget_temporary_buffer function template
The uninitialized_copy function template is like the copy algorithm, except the result iterator is assumed to point to uninitialized memory. The range [first, last) is copied to result using placement new. See Alsoraw_storage_iterator class template, uninitialized_fill function template, copy in <algorithm>, new operator
The uninitialized_fill function template is like the fill algorithm, except that it fills uninitialized memory. Every item in the range [first, last) is constructed as a copy of x using placement new. See Alsoraw_storage_iterator class template, uninitialized_copy function template, uninitialized_fill_n function template, fill in <algorithm>, new keyword
The uninitialized_fill_n function template is like the fill_n algorithm, except it fills uninitialized memory. Starting with first, n copies of x are constructed using placement new. See Alsoraw_storage_iterator class template, uninitialized_fill function template, fill_n in <algorithm>, new keyword |