(allocator 4) macro

本版本简单使用宏定义 进行语句包裹

说白了就是调用的时候懒一点

#pragma once
#include
class allocator
{
public:
	void* allocate(size_t size)
	{
		obj* p;
		if (!freeStore)
		{
			size_t chunk = size * BLOCK_SIZE;
			freeStore = p =
				(obj*)malloc(chunk);

			for (int i = 0; i < BLOCK_SIZE - 1; ++i)
			{
				p->next = (obj*)((char*)p + size);
				p = p->next;
			}
			p->next = nullptr;
		}
		p = freeStore;
		freeStore = freeStore->next;
		return p;
	}
	void deallocate(void* pdead, size_t size)
	{
	((obj*)pdead)->next = freeStore;
		freeStore = (obj*)pdead;
	}
private:
	struct obj {
		struct obj* next;
	};
private:
	const int BLOCK_SIZE = 5;
	obj* freeStore = nullptr;
};

#define DECLARE_POOL_ALLOC() \
protected:\
	static allocator my_Alloc;\
public:\
	 void* operator new(size_t size) {return my_Alloc.allocate(size);}\
	 void operator delete(void* pdead, size_t size){return my_Alloc.deallocate(pdead, size);}

#define IMPLEMENT_POOL_ALLOC(class_name)\
allocator class_name::my_Alloc;

new_handler

new时无法成功调用的函数(几率很小)

编译器不同new不成功的处理方式不一样

有的会抛出异常  有的会返回0

std::nothrow  可以使new返回0  new(std::nothrow) 

#define NEW_HANDLER_
#ifdef NEW_HANDLER_
#include
#include
#include
void noMemory()
{
	std::cout << "out of memory";
	abort();
}
int main()
{
	std::set_new_handler(noMemory);
	int* p = new(std::nothrow) int[10000000000000000];
	assert(p != 0);
}
#endif // new_handler

 new 不成功时可以由用户自定义一个函数去调用

设置方法就是  std::set_new_handler(  void (*func) () );

 

你可能感兴趣的:(c++语言,c++,开发语言)