【问题标题】:boost::interprocess -- std::string vs. std::vectorboost::interprocess -- std::string 与 std::vector
【发布时间】:2011-09-17 16:58:19
【问题描述】:

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

【问题讨论】:

    标签: c++ boost stl interprocess


    【解决方案1】:

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

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

    附: stringvector 之间有很多不同之处。最重要也是最少被提及的是string is not a container from standard's point of view

    【讨论】:

    • 非常感谢 ^^,是的,我忘了提到 std::vector 的行为完全符合我的预期 ^^ 但在此之前我从未听说过 SSO 的任何消息^^
    猜你喜欢
    • 2018-07-24
    • 2011-11-18
    • 2014-01-11
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2017-01-08
    相关资源
    最近更新 更多