【发布时间】:2011-09-17 16:58:19
【问题描述】:
我使用 boost::interprocess::managed_(windows_)shared_memory::construct 构造了一个进程间向量,该向量包含一个自己的类,该类有一个 std::string 类型的成员变量和另一个 std::vector 类型的成员变量,所以:
class myclass
{
public:
myclass()
{
}
std::string _mystring;
std::vector < int > _myintvector;
};
template < class _type >
struct typedefs
{
typedef boost::interprocess::managed_windows_shared_memory _memory;
typedef _memory::segment_manager _manager;
typedef boost::interprocess::allocator < _type, _manager > _allocator;
typedef boost::interprocess::vector < _type, _allocator > _vector;
};
typedef typedefs < myclass > tdmyclass;
int main ()
{
using namespace boost::interprocess;
managed_windows_shared_memory mem ( open_or_create, "mysharedmemory", 65536 );
tdmyclass::_vector * vec = mem.construct < tdmyclass::_vector > ( "mysharedvector" ) ( mem.get_segment_manager() );
myclass mytemp;
mytemp._mystring = "something";
mytemp._myintvector.push_back ( 100 );
mytemp._myintvector.push_back ( 200 );
vec->push_back ( mytemp );
/* waiting for the memory to be read is not what this is about,
so just imagine the programm stops here until everything we want to do is done */
}
我只是为了测试而这样做,我不希望 std::string 和 std::vector 都可以工作,但是,如果我从另一个进程中读取它,std::string 实际上可以工作,它包含我分配的字符串.这真让我吃惊。 另一边的 std::vector 只能部分工作,size() 返回的值是正确的,但是如果我想访问迭代器或使用 operator[],程序会崩溃。
所以,我的问题是,为什么会这样?我的意思是,我从未真正阅读过 Visual Studio SDK 的 STL 实现,但 std::string 不只是一个 std::vector 具有适合字符串的额外功能吗?他们不是都使用 std::allocator - 这意味着 std::string 和 std::vector 都不能在共享内存中工作吗?
对此进行谷歌搜索并不会真正产生任何结果,而是 boost::interprocess::vector,而这不是我搜索的内容。所以我希望有人能给我一些关于发生了什么的细节^^
PS:如果我在上面的代码中打错了,请原谅我,我只是在这个页面编辑器中写的,我有点习惯于自动完成我的 IDE ^^
【问题讨论】:
标签: c++ boost stl interprocess