跳轉至內容

更多 C++ 習語/自由函式分配器

來自 Wikibooks,開放世界開放書籍

自由函式分配器

[編輯 | 編輯原始碼]

允許容器使用自定義分配器,而無需建立新的型別

C++ 標準分配器存在嚴重問題,因為它們會更改容器的底層型別。

解決方案和示例程式碼

[編輯 | 編輯原始碼]

這種習語優於 std::分配器的工作方式,整個習語在此概述。

struct user_allocator_nedmalloc
{
	typedef std::size_t size_type;
	typedef std::ptrdiff_t difference_type;
	
	static inline char* malloc(const size_type bytes) {
		return reinterpret_cast<char*>(nedmalloc(bytes));
	}
	
	static inline void free(char* const block) {
		nedfree(block);
	}
};

已知用法

[編輯 | 編輯原始碼]
  • boost::ptr_container
[編輯 | 編輯原始碼]

參考文獻

[編輯 | 編輯原始碼]
華夏公益教科書