Allocators - return p; } void deallocate(pointer p,...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Allocators In previous issues, we've looked at some of the standard containers (such as vector) found in the C++ Standard Library. One of the interesting issues that comes up is how such containers manage memory. It turns out that containers use what is called a standard allocator, defined in <memory>. To see a bit of how this works, we will devise a custom allocator: #include <vector> #include <cstddef> #include <iostream> using namespace std; template <class T> class alloc { public: typedef T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; void construct(pointer p, const_reference val) { new (p) T(val); } void destroy(pointer p) { p->~T(); } pointer allocate(size_type sz, void* vp = 0) { pointer p = static_cast<pointer>(operator new(sz * sizeof(value_type))); cout << "allocate " << (unsigned long)p << endl;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: return p; } void deallocate(pointer p, size_type) { cout &lt;&lt; &quot;deallocate &quot; &lt;&lt; (unsigned long)p &lt;&lt; endl; operator delete(p); } }; This allocator overrides the default allocator for vector, and is specified by saying: vector&lt;int, alloc&lt;int&gt; &gt; v; The allocator template establishes a series of standard internal types such as &quot;pointer&quot;. The real work gets done in allocate() and deallocate(), which are used to allocate N objects of type T. The standard allocator uses operator new() and operator delete() to actually allocate/deallocate memory. Normally you don't need to worry too much about this area, but sometimes for reasons of speed and space you may wish to construct your own allocator for use with standard containers. For example, allocators can be written that are efficient for very small objects, or that use shared memory, or that use memory from pre-allocated pools of objects....
View Full Document

This note was uploaded on 02/27/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue University-West Lafayette.

Page1 / 2

Allocators - return p; } void deallocate(pointer p,...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online