如何声明和使用重载池运算符删除?

发布于 2024-08-22 16:09:56 字数 649 浏览 1 评论 0原文

我想知道如何适应C++-的第11.14节FAQ-lite 到数组。

基本上,我想要这样的东西:

class Pool {
public:
  void* allocate(size_t size) {...}
  void deallocate(void* p, size_t size) {...}
};

void* operator new[](size_t size, Pool& pool) { return pool.allocate(size); }
void operator delete[](void* p, size_t size, Pool& pool) { pool.deallocate(p, size); }

struct Foo {...};

int main() {
  Pool pool;

  Foo* manyFoos = new (pool) Foo [15];

  /* ... */

  delete [] (pool) manyFoos;
}

但是,我无法找出声明和调用此运算符delete[](池)的正确语法。有人可以帮忙吗?

I would like to know how to adapt section 11.14 of the C++-FAQ-lite to arrays.

Basically, I would want something like this:

class Pool {
public:
  void* allocate(size_t size) {...}
  void deallocate(void* p, size_t size) {...}
};

void* operator new[](size_t size, Pool& pool) { return pool.allocate(size); }
void operator delete[](void* p, size_t size, Pool& pool) { pool.deallocate(p, size); }

struct Foo {...};

int main() {
  Pool pool;

  Foo* manyFoos = new (pool) Foo [15];

  /* ... */

  delete [] (pool) manyFoos;
}

However, I have not been able to figure out the correct syntax to declare and call this operator delete[] (pool). Can anybody help here?

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

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

发布评论

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

评论(2

断肠人 2024-08-29 16:09:56

首先对各个对象调用 dtor,然后使用:

for (int i = 0; i < 15; ++i) manyFoos[ i ]->~Foo();
operator delete[] (manyFoos, pool);

您可以再次阅读整个常见问题解答项目,您会在那里找到它。

Call the dtors on the individual objects first and then use:

for (int i = 0; i < 15; ++i) manyFoos[ i ]->~Foo();
operator delete[] (manyFoos, pool);

You can read the whole FAQ item again and you will find it there.

贩梦商人 2024-08-29 16:09:56

这是不可能的。 Bjarne 认为,你永远无法正确地找出正确的池。他的解决方案是:您必须手动调用所有析构函数,然后找出正确的池才能手动释放内存。

参考文献:

Bjarne 的常见问题解答:是否有展示位置删除?

相关 C++ 标准部分:

3.7.3.2.2 删除表达式仅考虑带有 size_t 类型参数的成员运算符删除函数。

5.3.5.1 删除表达式语法不允许额外的参数。

It is impossible. Bjarne reasons that you'll never get it right figuring out the correct pool. His solution is: you must manually call all destructors and then figure out the correct pool to be able to deallocate the memory manually.

References:

Bjarne's FAQ: Is there a placement delete?

Relevant C++ standard sections:

3.7.3.2.2 Only member operator delete functions with an argument of size_t type are considered for delete expressions.

5.3.5.1 Delete expression syntax does not allow extra parameters.

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