{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}


Allocators - return p void deallocate(pointer p size_type...

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 Document Right 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 << "deallocate " << (unsigned long)p << endl; operator delete(p); } }; This allocator overrides the default allocator for vector, and is specified by saying: vector<int, alloc<int> > v; The allocator template establishes a series of standard internal types such as "pointer". 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

{[ snackBarMessage ]}

Page1 / 2

Allocators - return p void deallocate(pointer p size_type...

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

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