Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1073714
  • 博文数量: 77
  • 博客积分: 11498
  • 博客等级: 上将
  • 技术积分: 1840
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-04 11:10
文章分类

全部博文(77)

文章存档

2011年(1)

2010年(16)

2009年(5)

2008年(55)

分类: C/C++

2008-08-29 19:38:01

The Mallocator

A common question from programmers who have an intermediate amount of experience with using the STL is, "How do I write an STL allocator?".  Writing an STL allocator is not especially difficult - only two member functions are interesting, allocate() and deallocate().  However, STL allocators must satisfy a number of other requirements (given by section 20.1.5 of the International Standard for C++,
ISO/IEC 14882:2003), and the code to do so takes roughly 80 editor lines.  Figuring out the code from the requirements can be overwhelming, but once you see the code, it's easy.

One thing some programmers try is to derive from std::allocator.  I recommend against this; it's more trouble than it's worth.  Looking at std::allocator's implementation is also painful.

Therefore, I've written an example STL allocator, whose purpose in life is to wrap malloc() and free(), which I've imaginatively called Mallocator.  I've carefully implemented all of the integer overflow checks and so forth that would be required in real production code.  And I've exhaustively commented which parts of Mallocator are boilerplate (common to all, virtually all, or all stateless allocators), and which parts you would have to customize.  Hopefully, this should demystify the implementation of STL allocators:

C:\Temp>type mallocator.cpp

// The following headers are required for all allocators.
#include   // Required for size_t and ptrdiff_t and NULL
#include        // Required for placement new and std::bad_alloc
#include // Required for std::length_error

// The following headers contain stuff that Mallocator uses.
#include   // For malloc() and free()
#include   // For std::cout
#include    // For std::endl

// The following headers contain stuff that main() uses.
#include       // For std::list

template class Mallocator {
public:
    // The following will be the same for virtually all allocators.
    typedef T * pointer;
    typedef const T * const_pointer;
    typedef T& reference;
    typedef const T& const_reference;
    typedef T value_type;
    typedef size_t size_type;
    typedef ptrdiff_t difference_type;

    T * address(T& r) const {
        return &r;
    }

    const T * address(const T& s) const {
        return &s;
    }

    size_t max_size() const {
        // The following has been carefully written to be independent of
        // the definition of size_t and to avoid signed/unsigned warnings.
        return (static_cast(0) - static_cast(1)) / sizeof(T);
    }

    // The following must be the same for all allocators.
    template struct rebind {
        typedef Mallocator other;
    };

    bool operator!=(const Mallocator& other) const {
        return !(*this == other);
    }

    void construct(T * const p, const T& t) const {
        void * const pv = static_cast(p);
        new (pv) T(t);
    }

    void destroy(T * const p) const; // Defined below.

    // Returns true if and only if storage allocated from *this
    // can be deallocated from other, and vice versa.
    // Always returns true for stateless allocators.
    bool operator==(const Mallocator& other) const {
        return true;
    }

    // Default constructor, copy constructor, rebinding constructor, and estructor.
    // Empty for stateless allocators.
    Mallocator() { }

    Mallocator(const Mallocator&) { }

    template Mallocator(const Mallocator&) { }

    ~Mallocator() { }

    // The following will be different for each allocator.
    T * allocate(const size_t n) const {
        // Mallocator prints a diagnostic message to demonstrate
        // what it's doing. Real allocators won't do this.
        std::cout << "Allocating " << n << (n == 1 ? " object" : "objects")
            << " of size " << sizeof(T) << "." << std::endl;

        // The return value of allocate(0) is unspecified.
        // Mallocator returns NULL in order to avoid depending
        // on malloc(0)'s implementation-defined behavior
        // (the implementation can define malloc(0) to return NULL,
        // in which case the bad_alloc check below would fire).
        // All allocators can return NULL in this case.
        if (n == 0) {
            return NULL;
        }

        // All allocators should contain an integer overflow check.
        // The Standardization Committee recommends that std::length_error
        // be thrown in the case of integer overflow.
        if (n > max_size()) {
            throw std::length_error("Mallocator::allocate() - Integer verflow.");
        }

        // Mallocator wraps malloc().
        void * const pv = malloc(n * sizeof(T));

        // Allocators should throw std::bad_alloc in the case of memory allocation failure.
        if (pv == NULL) {
            throw std::bad_alloc();
        }

        return static_cast(pv);
    }

    void deallocate(T * const p, const size_t n) const {
        // Mallocator prints a diagnostic message to demonstrate
        // what it's doing. Real allocators won't do this.
        std::cout << "Deallocating " << n << (n == 1 ? " object" : "objects")
            << " of size " << sizeof(T) << "." << std::endl;

        // Mallocator wraps free().
        free(p);
    }

    // The following will be the same for all allocators that ignore hints.
    template T * allocate(const size_t n, const U * /* const hint */) const {
        return allocate(n);
    }

    // Allocators are not required to be assignable, so
    // all allocators should have a private unimplemented
    // assignment operator. Note that this will trigger the
    // off-by-default (enabled under /Wall) warning C4626
    // "assignment operator could not be generated because a
    // base class assignment operator is inaccessible" within
    // the STL headers, but that warning is useless.
private:
    Mallocator& operator=(const Mallocator&);
};

// A compiler bug causes it to believe that p->~T() doesn't reference p.

#ifdef _MSC_VER
    #pragma warning(push)
    #pragma warning(disable: 4100) // unreferenced formal parameter
#endif

// The definition of destroy() must be the same for all allocators.
template void Mallocator::destroy(T * const p) const {
    p->~T();
}

#ifdef _MSC_VER
    #pragma warning(pop)
#endif

int main() {
    using namespace std;

    cout << "Constructing l:" << endl;

    list > l;

    cout << endl << "l.push_back(1729):" << endl;

    l.push_back(1729);

    cout << endl << "l.push_back(2161):" << endl;

    l.push_back(2161);

    cout << endl;

    for (list >::const_iterator i = l.begin(); i != l.end(); ++i) {
        cout << "Element: " << *i << endl;
    }

    cout << endl << "Destroying l:" << endl;
}

C:\Temp>cl /EHsc /nologo /W4 mallocator.cpp
mallocator.cpp

C:\Temp>mallocator
Constructing l:
Allocating 1 object of size 4.
Allocating 1 object of size 12.

l.push_back(1729):
Allocating 1 object of size 12.

l.push_back(2161):
Allocating 1 object of size 12.

Element: 1729
Element: 2161

Destroying l:
Deallocating 1 object of size 12.
Deallocating 1 object of size 12.
Deallocating 1 object of size 12.
Deallocating 1 object of size 4.

To explain this output:
The object of size 4 is the aux object.
The objects of size 12 are doubly-linked list nodes.

In VC's implementation, default-constructed lists allocate a sentinel node, which is where end iterators point.  (End iterators have to be decrementable, so they can't point at NULL.)

Stephan T. Lavavej

Visual C++ Libraries Developer
阅读(1997) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~