2011-06-18 273 views
1

我用boost :: interprocess :: managed_(windows_)shared_memory :: construct来构造一个持有自己类的进程间向量,该类有一个成员变量类型的std :: string和其他类型的std ::的载体,所以:boost :: interprocess - 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 ::向量是工作,但是,如果我从另一个进程读取它,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的自动完成^^

回答

6

std::string因为您的标准库实现使用小字符串优化(SSO)而起作用。这意味着字符串"something"的值被复制到字符串对象本身中,没有任何动态内存分配。因此,您可以从其他进程中读取它。对于更长的字符串(尝试30个字符),它不会工作。

std::vector不起作用,因为它不允许按标准使用SSO。它在第一个进程的地址空间中分配内存,但这个内存不能被其他进程访问。 .size()的作品,因为它存储里面的矢量本身,作为一个成员。

P.S. stringvector之间有很多不同之处。最重要的一个,也是最少提到的那个,就是string is not a container from standard's point of view

+0

没错。所以它不适用于更长的字符串。检查它:_) – sehe

+0

非常感谢^^和是我忘记提及std :: vector的行为完全符合我的预期^^但是我从来没有听说过任何来自SSO的^^ – Andy

相关问题