1
我有一個boost::interprocess Containers of containers類型的示例演示程序。 但我喜歡在我的進程內存中使用這個類也是一個普通的類。 有人可以幫我寫一個構造函數,它不需要任何參數就可以在當前進程內存中初始化類。boost :: interprocess不在共享內存中的容器容器
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <shmfw/serialization/interprocess_vector.hpp>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
using namespace boost::interprocess;
//Alias an STL-like allocator of ints that allocates ints from the segment
typedef allocator<int, managed_shared_memory::segment_manager> ShmemAllocator;
//Alias a vector that uses the previous STL-like allocator
typedef vector<int, ShmemAllocator> MyVector;
typedef allocator<void, managed_shared_memory::segment_manager > void_allocator;
class MyStruct {
public:
MyVector myVector;
//Since void_allocator is convertible to any other allocator<T>, we can simplify
//the initialization taking just one allocator for all inner containers.
MyStruct (const void_allocator &void_alloc)
: myVector (void_alloc)
{}
// Thats what I like to have
//MyStruct()
// : myVector (??)
//{}
};
int main() {
// I would like to have something like that working and also the shm stuff below
// MyStruct x;
managed_shared_memory segment;
//A managed shared memory where we can construct objects
//associated with a c-string
try {
segment = managed_shared_memory(create_only, "MySharedMemory", 65536);
} catch (...){
segment = managed_shared_memory(open_only, "MySharedMemory");
}
//Initialize the STL-like allocator
const ShmemAllocator alloc_inst (segment.get_segment_manager());
MyStruct *myStruct_src = segment.find_or_construct<MyStruct> ("MyStruct") (alloc_inst);
srand (time(NULL));
myStruct_src->myVector.push_back (rand());
MyStruct *myStruct_des = segment.find_or_construct<MyStruct> ("MyStruct") (alloc_inst);
for (size_t i = 0; i < myStruct_src->myVector.size(); i++) {
std::cout << i << ": " << myStruct_src->myVector[i] << " = " << myStruct_des->myVector[i] << std::endl;
if(myStruct_src->myVector[i] != myStruct_des->myVector[i]) {
std::cout << "Something went wrong!" << std::endl;
}
}
//segment.destroy<MyVector> ("MyVector");
return 0;
}
的最佳解決方案,感謝 – Max 2014-10-23 12:35:17
有誰知道怎麼這個答案與scoped_allocator結合? - >該問題更詳細地發佈在http://stackoverflow.com/q/28608185/1358042 謝謝 – Max 2015-02-22 16:23:13