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

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

本文关键字:std vs vector string interprocess boost      更新时间:2023-10-16

我使用boost::interprocess::managed_(windows_)shared_memory:

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::字符串实际上起作用,它包含我分配的字符串。这真的让我很惊讶。另一边的std::vector只能部分工作,size()返回的值是正确的,但如果我想访问迭代器或使用运算符[],程序会崩溃。

所以,我的问题是,为什么会这样?我的意思是,我从来没有真正阅读过Visual Studio SDK的STL实现,但std::string不就是一个std::向量吗?它们不是都使用std::分配器吗?这意味着std::string和std::vector在共享内存中都不能工作?

在谷歌上搜索除了boost::interprocess::vector之外,什么结果都没有,这不是我搜索的。所以我希望有人能给我一些关于发生了什么的细节

附言:如果我在上面的代码中拼写错误,请原谅,我现在刚刚在这个页面编辑器中写了它,我有点习惯于自动完成我的IDE ^^

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

std::vector不起作用,因为标准中不允许使用SSO。它在第一个进程的地址空间中分配内存,但其他进程无法访问此内存。.size()之所以有效,是因为它作为一个成员存储在向量本身内部。

附言:CCD_ 5和CCD_。最重要的一点,也是最不被提及的一点是,从标准的角度来看,string不是容器。