开发者

How do you declare and use an overloaded pool operator delete?

开发者 https://www.devze.com 2022-12-20 21:36 出处:网络
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:

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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消