【发布时间】:2014-01-23 14:09:07
【问题描述】:
我正在研究内存池/内存分配器的实现,我正在将它设置在一个庄园中,只有一个特殊的“客户端”对象类型可以从池中提取。客户端可以直接构建到池中,或者它可以将池用于动态内存调用,或者理论上可以两者兼而有之。 我希望能够重载 operator new 和 operator delete 以调用我的池“alloc()”和“free()”函数,以便获取构建对象所需的内存。
我遇到的主要问题之一是通过调用我编写的 pool->free() 函数来让我的操作员 delete 能够释放内存。我想出了一个技巧,通过将池传递给构造函数并让析构函数完成释放工作来修复它。这一切都很好而且很花哨,直到有人需要从这个类继承并根据自己的需要重写析构函数,然后忘记进行内存释放。这就是为什么我想把它全部封装在操作符中,这样功能就被隐藏起来并默认继承。
我的代码在 GitHub 上:https://github.com/zyvitski/Pool
我对 Client 的类定义如下:
class Client
{
public:
Client();
Client(Pool* pool);
~Client();
void* operator new(size_t size,Pool* pool);
void operator delete(void* memory);
Pool* m_pPool;
};
而实现是:
Client::Client()
{
}
Client::Client(Pool* pool)
{
m_pPool = pool;
}
Client::~Client()
{
void* p = (void*)this;
m_pPool->Free(&p);
m_pPool=nullptr;
}
void* Client::operator new(size_t size, Pool* pool)
{
if (pool!=nullptr) {
//use pool allocator
MemoryBlock** memory=nullptr;
memory = pool->Alloc(size);
return *memory;
}
else throw new std::bad_alloc;
}
void Client::operator delete(void* memory)
{
//should somehow free up the memory back to the pool
// the proper call will be:
//pool->free(memory);
//where memory is the address that the pool returned in operator new
}
这是我目前正在使用的示例 Main():
int main(int argc, const char * argv[]){
Pool* pool = new Pool();
Client* c = new(pool) Client(pool);
/*
I'm using a parameter within operator new to pass the pool in for use and i'm also passing the pool as a constructor parameter so i can free up the memory in the destructor
*/
delete c;
delete pool;
return 0;
}
到目前为止,我的代码可以正常工作,但我想知道是否有更好的方法来实现这一点? 请让我知道我所要求/做的任何事情是不可能的、不好的做法或只是愚蠢的。我现在在 MacBook Pro 上,但如果可能的话,我想保持我的代码跨平台。
如果您有任何问题可以帮助我,请告诉我。
当然,提前感谢任何可以提供帮助的人。
【问题讨论】:
标签: c++ memory-management new-operator delete-operator placement-new