我想利用以下广告功能boost::fast_pool_allocator
(see Boost Pool 的 Boost 文档):
例如,您可能会遇到这样的情况:您想要分配一个
一堆小物体在一个点上,然后到达你的一个点
不再需要它们的程序。使用池接口,
你可以选择运行它们的析构函数或者只是把他们扔进
遗忘...
(See here对于这个报价。)
关键短语是让他们被遗忘. I do not希望在这些对象上调用析构函数。
(原因是我有数百万个微小对象,它们在堆上形成了一个极其复杂的所有权网络,当单个最父对象离开堆栈时,我的程序需要大约 20 分钟才能调用所有析构函数。我不需要调用这些析构函数,因为没有期望的副作用,并且所有内存都包含在boost::pool
.)
不幸的是,尽管上述文档做出了承诺,并且boost::pool
概念,我找不到一种方法来阻止调用托管对象的析构函数。
该问题很容易在一个小示例程序中隔离:
class Obj
{
public:
~Obj()
{
// Placing a breakpoint here indicates that this is *always* reached
// (except for the crash scenario discussed below)
int m = 0;
}
};
typedef std::map<int, Obj, std::less<int>,
boost::fast_pool_allocator<std::pair<int const, Obj>>>
fast_int_to_int_map;
class Foo
{
public:
~Foo()
{
// When the following line is uncommented, the program CRASHES
// when the destructor is exited - because the Obj destructors
// are called on the invalid Obj ghost instances
//boost::singleton_pool<boost::fast_pool_allocator_tag,
// sizeof(std::pair<int const, Obj>)>::purge_memory();
}
fast_int_to_int_map mmap;
};
void mfoo()
{
// When this function exits, the Foo instance goes off the stack
// and its destructor is called, in turn calling the destructors
// of the Obj instances - this is NOT desired!
Foo foo;
foo.mmap[0] = Obj();
foo.mmap[1] = Obj();
}
int main()
{
mfoo();
// The following line deallocates the memory of the pool just fine -
// but does nothing to prevent the destructors of the Obj instances
// from being called
boost::singleton_pool<boost::fast_pool_allocator_tag,
sizeof(std::pair<int const, Obj>)>::purge_memory();
}
正如代码注释中所述,析构函数Obj
由管理的实例boost::pool
总是被调用。
我该怎么做才能引用 Boost Pool 文档中的有希望的内容,drop them off into oblivion
, 成真?