gpt4 book ai didi

c++ - boost::interprocess -- std::string 与 std::vector

转载 作者:行者123 更新时间:2023-11-30 00:40:17 24 4
gpt4 key购买 nike

我使用 boost::interprocess::managed_(windows_)shared_memory::construct 构造了一个持有自己类的进程间 vector ,它有一个 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() 之所以有效,是因为它作为成员存储在 vector 本身的内部

附言stringvector 之间有很多区别。最重要也是最少提及的是string is not a container from standard's point of view。 .

关于c++ - boost::interprocess -- std::string 与 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6394959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com