【发布时间】:2014-05-21 10:58:28
【问题描述】:
我想利用boost::fast_pool_allocator 的以下广告功能(请参阅the Boost documentation for Boost Pool):
例如,您可能遇到想要分配一个 一堆小物体在一个点,然后到达你的一个点 不再需要它们的程序。使用池接口, 你可以选择运行它们的析构函数或者只是把它们放到 遗忘...
(请参阅 here 获取此报价。)
关键短语是让他们被遗忘。我不想要在这些对象上调用析构函数。
(原因是我有数百万个微小的对象,它们在堆上形成了一个极其复杂的所有权网络,当单个父级对象离开时,我的程序需要大约 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();
}
如代码 cmets 中所述,始终调用由 boost::pool 管理的 Obj 实例的析构函数。
我能做些什么来让 Boost Pool 文档中的有希望的引述 drop them off into oblivion 成真?
【问题讨论】: