嵌入式指针实现代码
// ConsoleApplication7.cpp : 定义控制台应用程序的入口点。 #include "stdafx.h" #include<iostream> using namespace std; class myallocator { public: void* allocate(size_t size) { obj *tmplink; if (free_allocator == nullptr) { size_t realsize = count*size; free_allocator = (obj*)malloc(realsize); tmplink = free_allocator; for (int i = 0; i < count - 1; ++i) { tmplink->next = (obj*)(tmplink+size); tmplink = tmplink->next; } tmplink->next = nullptr; } tmplink = free_allocator; free_allocator = free_allocator->next; return tmplink; } void deallocate(void* phead) { ((obj*)phead)->next = free_allocator; free_allocator =(obj*)phead; } struct obj { struct obj* next; }; private: int count=10; obj* free_allocator = nullptr; }; class A { public: static myallocator my; void* operator new(size_t size) { return my.allocate(size); } void operator delete(void * phead) { return my.deallocate(phead); } private: int x; int y; }; myallocator A::my; int main() { A * a[100]; for (int i = 0; i < 15; i++) { a[i] = new A(); cout << a[i] << endl; } for (int i = 0; i < 15; i++) { delete a[i]; } return 0; }