[英]Convert boost::container::boost basic_string to std::string
Is there a simple way to do this? 有一个简单的方法吗? I've tried the following:
我尝试过以下方法:
typedef allocator<char,managed_shared_memory::segment_manager>
CharAllocator;
typedef boost::container::basic_string<char, std::char_traits<char>, CharAllocator>
my_basic_string;
std::string s(my_basic_string);
As @TC has said, you should use: 正如@TC所说,你应该使用:
std::string s(my_basic_string.data(), my_basic_string.size());
or 要么
std::string s(my_basic_string.begin(), my_basic_string.end());
I prefer the second, but both will work. 我更喜欢第二种,但两种都可以。
Just copy element-wise (which any decent standard library implementation optimizes into memcpy
): 只需复制元素(任何体面的标准库实现优化到
memcpy
):
#include <boost/interprocess/managed_shared_memory.hpp>
#include <iostream>
using namespace boost::interprocess;
typedef allocator<char, managed_shared_memory::segment_manager> CharAllocator;
typedef boost::container::basic_string<char, std::char_traits<char>, CharAllocator> my_shared_string;
std::string s(my_shared_string const& ss) {
return std::string(ss.begin(), ss.end());
}
I called the string "my_shared_string" (because it's not any more "basic" than std::string). 我调用了字符串“my_shared_string”(因为它不再是std :: string的“基本”)。 In fact it's good to notice this has everything to do with containers with custom allocators, and nothing with std::string or Boost Interprocess in particular:
实际上,值得注意的是,这与使用自定义分配器的容器有关,而且特别是std :: string或Boost Interprocess没有任何内容:
typedef std::basic_string<char, std::char_traits<char>, CharAllocator> my_shared_string;
behaves exactly the same for the given problem; 对于给定的问题,行为完全相同; So does eg:
例如:
typedef std::vector<char, CharAllocator> my_shared_vector;
std::vector<char> v(my_shared_vector const& ss) {
return std::vector<char>(ss.begin(), ss.end());
}
Changed according to comments from @TC 根据@TC的评论改变了
You may use this: 你可以用这个:
std::string s(my_basic_string.c_str(), my_basic_string.size());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.