Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 505
wizurd Avatar asked Jun 17 '15 22:06

wizurd


2 Answers

As @T.C. has said, you should use:

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.

like image 164
Marshall Clow Avatar answered Nov 19 '22 23:11

Marshall Clow


Just copy element-wise (which any decent standard library implementation optimizes into 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). 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:

typedef std::basic_string<char, std::char_traits<char>, CharAllocator> my_shared_string;

behaves exactly the same for the given problem; So does e.g.:

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());
}
like image 24
sehe Avatar answered Nov 19 '22 21:11

sehe