《STL原始碼剖析》-- defalloc.h

凝霜發表於2011-07-27
// Filename:    defalloc.h

// Comment By:  凝霜
// E-mail:      mdl2009@vip.qq.com
// Blog:        http://blog.csdn.net/mdl13412

/*
 *
 * Copyright (c) 1994
 * Hewlett-Packard Company
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Hewlett-Packard Company makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 *
 */

// 這個檔案提供原始的HP預設allocator, 僅僅是為了向後相容
//
// 不要使用這個檔案,除非你使用一個需要HP-style allocator的舊容器
// SGI STL使用一個不同的allocator介面
// SGI-style的allocator不針對物件型別進行引數化, 他使用void *指標

#ifndef DEFALLOC_H
#define DEFALLOC_H

#include <new.h>
#include <stddef.h>
#include <stdlib.h>
#include <limits.h>
#include <iostream.h>
#include <algobase.h>

// 如果記憶體分配失敗, 則直接退出程式
template <class T>
inline T* allocate(ptrdiff_t size, T*)
{
    set_new_handler(0);
    T* tmp = (T*)(::operator new((size_t)(size * sizeof(T))));
    if (tmp == 0) {
	cerr << "out of memory" << endl;
	exit(1);
    }
    return tmp;
}

template <class T>
inline void deallocate(T* buffer)
{
    ::operator delete(buffer);
}

// 標準的STL allocator介面
template <class T>
class allocator
{
public:
    // STL type_traits需要的標準定義
    typedef T value_type;
    typedef T* pointer;
    typedef const T* const_pointer;
    typedef T& reference;
    typedef const T& const_reference;
    typedef size_t size_type;
    typedef ptrdiff_t difference_type;


    pointer allocate(size_type n)
    {
	return ::allocate((difference_type)n, (pointer)0);
    }
    void deallocate(pointer p) { ::deallocate(p); }
    pointer address(reference x) { return (pointer)&x; }
    const_pointer const_address(const_reference x)
    {
	return (const_pointer)&x;
    }
    // 
    size_type init_page_size()
    {
	return max(size_type(1), size_type(4096/sizeof(T)));
    }
    size_type max_size() const
    {
	return max(size_type(1), size_type(UINT_MAX/sizeof(T)));
    }
};

// 僅使用void *型別的指標
class allocator<void>
{
public:
    typedef void* pointer;
};

#endif

相關文章