至於「如何寫一個allocator」,§ 20.6.9 [default.allocator]
具有這樣說std::allocator
:
#include <new>
// specialize for void:
template <> class allocator<void> {
public:
typedef void* pointer;
typedef const void* const_pointer;
// reference-to-void members are impossible.
typedef void value_type;
template <class U> struct rebind { typedef allocator<U> other; };
};
template <class T> class allocator {
public:
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;
typedef T value_type;
template <class U> struct rebind { typedef allocator<U> other; };
allocator() throw();
allocator(const allocator&) throw();
template <class U> allocator(const allocator<U>&) throw();
~allocator();
pointer address(reference x) const throw();
const_pointer address(const_reference x) const throw();
pointer allocate(size_type, allocator<void>::const_pointer hint = 0);
void deallocate(pointer p, size_type n) throw();
size_type max_size() const throw();
template<class U, class... Args>
void construct(U* p, Args&&... args);
template <class U>
void destroy(U* p);
};
你可能會想補充一點表現得更像new
和delete
我們幫助成員函數習慣於。
template<class... Args>
pointer alloc_and_constr(size_type n, Args&&... args);
template <class U>
pointer destr_and_dealloc(U* p);
我想一個更好的問題是,爲什麼你堅持做「噸小的malloc /免費事件的高嬰兒死亡率」。這幾乎肯定反映了一個糟糕的設計。請注意,沒有可移植的方法來替換'malloc',但是您可以使用另一個分配器(例如內存池),它與「malloc」一起運行。 –
作爲一個例子來澄清......如果你使用的'malloc(N)'其中'N <64'左右作爲一種方法將結果傳遞給調用者,你幾乎肯定會更好一個通過值結構或讓調用者傳遞一個指向目的地的指針(實際上兩者在現實世界的實現中是等價的)。對於這種小物體使用'malloc'唯一有意義的是當物體在記憶中靜止是必不可少的,例如,充當鏈接列表,樹等的一部分... –
@R。在我目前的生活中,我試圖建立一個離散事件模擬器。在以前的生活中,我在爲股票市場建立訂單時遇到了這個問題。有許多情況下必須跟蹤大量實體並隨機進入/退出系統。 –