如何声明和使用重载池运算符删除?
我想知道如何适应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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先对各个对象调用 dtor,然后使用:
您可以再次阅读整个常见问题解答项目,您会在那里找到它。
Call the dtors on the individual objects first and then use:
You can read the whole FAQ item again and you will find it there.
这是不可能的。 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.