boost :: interprocess - std :: string vs. std :: vector

And*_*ndy 1 c++ boost stl interprocess

我使用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 */
}
Run Code Online (Sandbox Code Playgroud)

我只是做了这个测试,我期望std :: string和std :: vector都没有工作,但是,如果我从另一个进程读取它,std :: string实际上工作,它包含我指定的字符串.这真让我感到惊讶.另一侧的std :: vector只能部分工作,size()返回的值是正确的,但是如果我想访问迭代器或者使用operator [],程序会崩溃.

所以,我的问题是,为什么会这样?我的意思是,我从来没有真正阅读过Visual Studio SDK的STL实现,但是std :: string只是一个std :: vector,其中包含适合字符串的额外函数吗?难道他们都不使用std :: allocator - 这意味着BOTH std :: string和std :: vector在共享内存中不起作用?

谷歌搜索这并不会导致除了boost :: interprocess :: vector之外的任何东西,这不是我搜索的内容.所以我希望有人可以给我一些关于什么事情的细节^^

PS:如果我在上面的代码中输了一个拼写错误,请原谅我,我现在只是在这个页面编辑器中写了它,而且我有点太习惯了我的IDE自动完成了^^

ybu*_*ill 7

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

std::vector不起作用,因为它不允许按标准使用SSO.它在第一个进程的地址空间中分配内存,但是其他进程无法访问此内存.该.size()作品,因为它存储里面的载体本身,作为一个成员.

PS string和之间存在很多差异vector.最重要的一个,也是最少提到的,从标准的角度来看,string不是一个容器.