Convert boost :: container :: boost basic_string to std :: string

Is there an easy way to do this? I 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);
+4
source share
3 answers

As @TC 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.

+5
source

Just copy the element-wise (that the implementation of any decent standard library is optimized in 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 named the string "my_shared_string" (because it is no more "basic" than std :: string). It’s actually good to notice that this is related to 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;

; :

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());
}
+1

@T.C.

:

std::string s(my_basic_string.c_str(), my_basic_string.size());
0

All Articles