标签:
这一节用到的小知识:
1.ptrdirr_t:
ptrdiff_t是C/C++标准库中定义的一个与机器相关的数据类型。ptrdiff_t类型变量通常用来保存两个指针减法操作的结果。ptrdiff_t定义在stddef.h(cstddef)这个文件内。ptrdiff_t通常被定义为long int类型。
2.non-trivial constructor/destructor:
意思是“非默认构造函数/析构函数”,这里的non-trivial指不是编译器自动生成的(函数)维基百科
我认为trivial更深层次的含义是构造和析构的东西都是在栈上分配的,其内存可以被栈自动回收,所以SGI STL的空间配置器std::alloc在做destroy时会先判断析构对像是不是trivial,如果对象是trivial,证明对象的所有成员分配在栈上,那么为了节省效率,可以不调用析构函数,由栈来自动回收内存。如果对象是non-trivial则需要调用每个对象的析构函数,释放堆上分配的内存。
3.operator new():
指对new的重载形式,它是一个函数,并不是运算符。对于operator new来说,分为全局重载和类重载,全局重载是void* ::operator new(size_t size),在类中重载形式 void* A::operator new(size_t size)。还要注意的是这里的operator new()完成的操作一般只是分配内存,事实上系统默认的全局::operator new(size_t size)也只是调用malloc分配内存,并且返回一个void*指针。而构造函数的调用(如果需要)是在new运算符中完成的。
4.由第三点可知,在空间配置器的new操作分为两步:allocate()函数分配内存,construct()函数把分配的内存初始化为一个个的模板类对象。
侯捷老师的书中介绍了空间配置器基本的接口(p43~44)。以下是一个简单的空间配置器实现:
cghAlloc.h:
#ifndef _CGH_ALLOC
#define _CGH_ALLOC
#include <new>
#include <cstddef>
#include <cstdlib>
#include <climits>
#include <iostream>
namespace CGH
{
template<class T>
inline T* _allocate(ptrdiff_t size, T*)
{
set_new_handler(0);
T* tmp = (T*)(::operator new((size_t)(size * sizeof(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);
}
template<class T1, class T2>
inline void _construct(T1* p, const T2& value)
{
new(p)T1(value); // 调用placement new,在指定的内存位置p处初始化T1对象,初始化T1对象时调用T1的复制构造函数
}
template<class T>
inline void _destroy(T* ptr)
{
ptr->~T();
}
template<class T>
class allocator
{
public:
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;
template<class U>
struct rebind
{
typedef allocator<U> other;
};
pointer allocate(size_type n, const void* hint = 0)
{
return _allocate((difference_type)n, (pointer)0);
}
void deallocate(pointer p, size_type n)
{
_deallocate(p);
}
void construct(pointer p, const T& value)
{
_construct(p, value);
}
void destroy(pointer p)
{
_destroy(p);
}
pointer address(reference x)
{
return (pointer)&x;
}
const_pointer const_address(const_reference x)
{
return (const_pointer)&x;
}
size_type max_size() const
{
return size_type(UINT_MAX / sizeof(T));
}
};
}
#endif测试空间配置器
allocator.cpp:
// allocator.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "cghAlloc.h"
#include <vector>
#include <iostream>
using namespace::std;
int _tmain(int argc, _TCHAR* argv[])
{
int arr[5] = { 0, 1, 2, 3, 4 };
//unsigned int i;
CGH::allocator<int> test;
CGH::allocator<int> test1;
vector<int, CGH::allocator<int>>iv(arr, arr + 5);
for (int i = 0; i < iv.size(); i++){
cout << iv[i] << ' ';
}
cout << endl;
system("pause");
return 0;
}
标签:
原文地址:http://blog.csdn.net/chengonghao/article/details/51329052