我想借的boost::fast_pool_allocator
以下通告功能的優勢(見the Boost documentation for Boost Pool):如何防止在由boost :: fast_pool_allocator管理的對象上調用析構函數?
例如,你可以有一個情況下,你要在一個點分配 一堆小物件,和然後到達您的 程序中的一個點,這些程序不再需要它們。使用游泳池接口, 您可以選擇運行自己的析構函數或只是把它們關進 遺忘 ...
(此報價見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();
}
如在代碼註釋所指出的,它們由boost::pool
管理的Obj
實例的析構函數總是調用。
我能做些什麼來使Boost Pool文檔drop them off into oblivion
有希望的引用成真?
有一個頂級對象,並且每個作爲容器的數據成員都通過所有嵌套對象使用自定義分配器等,因此沒有通過樹的層次結構丟失的單個路徑。然後,我簡單地讓單個頂層對象從堆棧中移出,並且*它的析構函數在所有內存池中調用'purge'。非常感謝這個答案 - 回想起來很明顯!當然,這是'malloc/free'和'new/delete'之間的巨大區別 - 前者不會調用構造函數和析構函數。我從不使用'malloc/free',所以沒有想到它。 –
我正在嘗試這個 - 你知道'boost :: default_user_allocator_malloc_free'分配器*將確保**構造函數**被調用嗎? –
我不知道 - 在你的例子中你明確地調用了構造函數。我認爲你會在你的實施中做類似的事情。 – Andy