首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >boost::interprocess -- std::string与std::vector

boost::interprocess -- std::string与std::vector
EN

Stack Overflow用户
提问于 2011-06-18 17:01:59
回答 1查看 951关注 0票数 1

我使用boost::interprocess::managed_(windows_)shared_memory::construct构造了一个包含自己的类的进程间向量,该类有一个std::string类型的成员变量和另一个std::vector类型的成员变量,因此:

代码语言:javascript
复制
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之外什么都没有,这不是我搜索的结果。所以我希望有人能给我一些关于发生了什么的细节^^

注:如果我在上面的代码中犯了一个打字错误,请原谅,我刚刚在这个页面编辑器中写了它,我有点习惯了自动补全我的IDE ^^

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-06-18 17:29:48

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

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

另外,stringvector有很多不同之处。最重要的,也是最少被提及的,就是string is from standard's point of view

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6394959

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档