繁体   English   中英

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

[英]boost::interprocess — std::string vs. std::vector

我用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的^^

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

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

PS在stringvector之间有很多区别。 从标准的角度来看 ,最重要的也是最不被提及的是string 不是容器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM