C++ primier 一书第18章
关于这个内存分配器基类有点不明白,特请教
源代码中的一部分
if (!free_store)
{
T * array = alloc_mem.allocate(chunk);
for(size_t i = 0; i != chunk; ++i)
add_to_freelist(&array); }
执行完后,应该是:
array[chunk-1]->next = array[chunk-2]free_store = array[chunk-1]
接着执行operator new(size_t sz)后续语句,应返回:
array[chunk-1] = Pfree_store = array[chunk-1]->next = array[chunk-2]
这个怎么是倒序添加,不是顺序添加
源代码template<class T>
class CachedObj
{
public:
void * operator new(size_t sz);
void operator delete(void* p, size_t sz);
virtual ~CachedObj() {}
protected:
T * next;
private:
static void add_to_freelist(T * p);
static allocator<T> alloc_mem;
static T * free_store;
static const size_t chunk;};
template<class T>
allocator<T> CachedObj<T>::alloc_mem;
template<class T>
T* CachedObj<T>::free_store = NULL;
template<class T>
const size_t CachedObj<T>::chunk = 64;
template<class T>
void *CachedObj<T>::operator new(size_t sz)
{
if(sz != sizeof(T))
return ::operator new(sz);
if (!free_store)
{
T * array = alloc_mem.allocate(chunk);
for(size_t i = 0; i != chunk; ++i)
add_to_freelist(&array);
}
T *p = free_store;
free_store = free_store->next;
return p;
}
template<class T>
void CachedObj<T>::operator delete(void * p,size_t sz)
{
if(p == NULL) return;
if(sz != sizeof(T))
{
::operator delete(p);
return;
}
add_to_freelist(static_cast<T*>(p));
}
template<class T>
void CachedObj<T>::add_to_freelist(T *p)
{
p->next = free_store; free_store = p;
}
关于这个内存分配器基类有点不明白,特请教
源代码中的一部分
if (!free_store)
{
T * array = alloc_mem.allocate(chunk);
for(size_t i = 0; i != chunk; ++i)
add_to_freelist(&array); }
执行完后,应该是:
array[chunk-1]->next = array[chunk-2]free_store = array[chunk-1]
接着执行operator new(size_t sz)后续语句,应返回:
array[chunk-1] = Pfree_store = array[chunk-1]->next = array[chunk-2]
这个怎么是倒序添加,不是顺序添加
源代码template<class T>
class CachedObj
{
public:
void * operator new(size_t sz);
void operator delete(void* p, size_t sz);
virtual ~CachedObj() {}
protected:
T * next;
private:
static void add_to_freelist(T * p);
static allocator<T> alloc_mem;
static T * free_store;
static const size_t chunk;};
template<class T>
allocator<T> CachedObj<T>::alloc_mem;
template<class T>
T* CachedObj<T>::free_store = NULL;
template<class T>
const size_t CachedObj<T>::chunk = 64;
template<class T>
void *CachedObj<T>::operator new(size_t sz)
{
if(sz != sizeof(T))
return ::operator new(sz);
if (!free_store)
{
T * array = alloc_mem.allocate(chunk);
for(size_t i = 0; i != chunk; ++i)
add_to_freelist(&array);
}
T *p = free_store;
free_store = free_store->next;
return p;
}
template<class T>
void CachedObj<T>::operator delete(void * p,size_t sz)
{
if(p == NULL) return;
if(sz != sizeof(T))
{
::operator delete(p);
return;
}
add_to_freelist(static_cast<T*>(p));
}
template<class T>
void CachedObj<T>::add_to_freelist(T *p)
{
p->next = free_store; free_store = p;
}