C++通过子类化内存池

发布于 2024-10-09 07:06:41 字数 946 浏览 0 评论 0原文

因此,我正在研究一种轻松内存池 C++ 对象的方法,只需对需要池的类进行最少的修改即可。

内存池本身是您可以在任何地方找到的标准品种,但我制作了此类:

  Poolable::Poolable(MemPool& lepool){
     mempool = &lepool;
  }

  Poolable::~Poolable(){
     mempool->returnMemory((char*)this);
  }

  void * Poolable::operator new(size_t size, MemPool& lepool){
     if(!lepool.initialised())
        lepool.initializeBasedOnSize(size);

     return lepool.getMemory(size);

  }

  void Poolable::operator delete(void * p){
     // do absolutely NOTHING
  }

用法:

  class SomeSubclass : public Poolable { /* boring details here */ };
  MemPool thepool(1000);
  SomeSubclass * woot = new(thepool) SomeSubclass(thepool);

我想将 returnMemory 调用(基本上释放池的一部分)放在删除运算符中,但不知道如何从 void* 参数获取实际池的地址。

相反,我通过将其放入析构函数来解决。我认为构造函数要求使用池分配该类,这意味着销毁总是意味着随后将取消分配。

这是第一个可行的解决方案,使用起来非常方便。然而,这样做可能是不好的风格,我很好奇是否有更好的解决方案来解决这个问题。

有人知道其中一个吗?

So I was working on a way to memory pool c++ objects easily with minimal modification needed to the class that needs to be pooled.

The memory pool itself is the standard variety you can find anywhere, but I've made this class:

  Poolable::Poolable(MemPool& lepool){
     mempool = &lepool;
  }

  Poolable::~Poolable(){
     mempool->returnMemory((char*)this);
  }

  void * Poolable::operator new(size_t size, MemPool& lepool){
     if(!lepool.initialised())
        lepool.initializeBasedOnSize(size);

     return lepool.getMemory(size);

  }

  void Poolable::operator delete(void * p){
     // do absolutely NOTHING
  }

usage:

  class SomeSubclass : public Poolable { /* boring details here */ };
  MemPool thepool(1000);
  SomeSubclass * woot = new(thepool) SomeSubclass(thepool);

I wanted to put the returnMemory call (which basically frees a part of the pool) in the delete operator, but have no idea how to get the actual pool's address from the void* argument.

Instead, I settled by putting it in the destructor. I figure that the constructor mandates that the class was allocated using the pool, which means destruction always implies unallocation will follow.

It's the first working solution, and it's quite convenient to use. However, doing that is probably bad style, and I'm curious if there are better solutions to the problem.

Does anybody know of one?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寂寞清仓 2024-10-16 07:06:41

另一种方法是让Poolable::operator newthepool分配内存,以便您可以使用通常的(非放置)new语句。在您的解决方案中,用户必须记住这些对象是通过某种特殊技术分配的,这会显示太多细节并给用户代码带来太多负担。

An alternative would be to make Poolable::operator new allocate memory from thepool so that you can use usual (non-placement) new statements. In your solution the user has to remember that those objects are to be allocated via some special technique, that's showing too much details and putting too much burden onto the user code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文