2010-04-07 55 views
7

這是一個令人尷尬的問題,但即使是boost.interprocess提供的精心編寫的文檔也不足以讓我弄清楚去做這個。C++的分配器,特別是將構造函數的參數傳遞給分配給boost :: interprocess :: cached_adaptive_pool的對象::

我已經是一個cached_adaptive_pool分配情況,我想用它來構造一個對象,沿構造函數的參數傳遞:

struct Test { 
    Test(float argument, bool flag); 
    Test(); 
}; 

// Normal construction 
Test obj(10, true); 
// Normal dynamic allocation 
Test* obj2 = new Test(20, false); 

typedef managed_unique_ptr< 
    Test, boost::interprocess::managed_shared_memory>::type unique_ptr; 

// Dynamic allocation where allocator_instance == cached_adaptive_pool, 
// using the default constructor 
unique_ptr obj3 = allocator_instance.allocate_one() 
// As above, but with the non-default constructor 
unique_ptr obj4 = allocator_instance ... ??? 

這很可能是關於如何使用我的一個失敗一般分配器對象。但是在任何情況下,我都看不到如何使用這個特定的分配器,在cached_adaptive_pool中指定的接口將構造器參數傳遞給我的對象。

cached_adaptive_pool有方法:void construct(const pointer & ptr, const_reference v)但我不明白這是什麼意思,我找不到使用它的例子。

我的頭一整天都在模板中游泳,所以即使答案很明顯,我們也會非常感激。

回答

1

cached_adaptive_pool有方法: 無效結構(常量指針& PTR, 爲const_reference V),但我不 明白這意味着什麼,並使用它,我無法找到 例子。

應該遵循的std::allocator接口,在這種情況下allocate()給你未初始化的內存和construct()調用放置新的給定的指針上的一個合適的塊。

喜歡的東西:

allocator_instance.construct(allocator_instance.allocate_one(), Test(30, true)); 

沒有使用這些池自己,雖然。在C++ 0x中,分配器應該能夠調用任何構造函數,而不僅僅是複製構造函數,所以它可能是boost的分配器已經在一定程度上支持這個。

a.construct(p, 30, true); //a C++0x allocator would allow this and call new (p) Test(30, true) 
+0

謝謝。第一種形式是我期望的答案,但是太困惑和疲倦,無法意識到自己。第二種形式'a.construct(p,30,true)'似乎沒有被這個特定的boost分配器支持。令人討厭的是,由於'cached_adaptive_pool.construct()'返回'void',我必須寫'allocator_t :: pointer obj = allocator.allocate_one(); allocator.construct(obj,Test(30,true))'?我不確定更糟糕的是,使用兩個語句進行一個簡單的操作,或者直接使用有點奇怪的放置位置。 – porgarmingduod 2010-04-07 22:47:52

+0

你可以做一個單獨的函數。 – UncleBens 2010-04-08 07:13:44

1

我想我總是可以用放置新的語法。這個想法是取消引用由分配器返回的智能指針(在本例中爲offset_ptr),然後將原始地址傳遞給new()。

unique_ptr obj = new(&(*allocator_instance.allocate_one())) Test(1,true) 

這是做到這一點的慣用方式?還有很多其他的地方在提供明確的支持,以避免使用新的位置,這讓我覺得沒有。無論如何,如果在不久的將來沒有更好的辦法,我會接受這個答案。

+0

什麼是&* ptr'序列? – UncleBens 2010-04-08 07:12:59

+0

當我測試它時,new只接受一個原始指針,而不是這些分配器返回的offset_ptr。 – porgarmingduod 2010-04-08 23:02:39

相關問題