Search code examples
c++boostshared-memoryinterprocess

Converting from std::string to "MyShmString" when sharing memory with boost::interprocess


I am following this boost::interprocess guide and this Stack Overflow thread in order to share std::string variables among different processes. Specifically, I have a function which recieves a std::string that should be shared among other processes:

void registerFailedTests(std::string failed_test_name) {

    boost::interprocess::permissions perm;
    perm.set_unrestricted();

    boost::interprocess::shared_memory_object::remove(unit_tests_constants::shm_failed_tests_list.c_str());
    boost::interprocess::managed_shared_memory managed_shm_failed_tests_list(boost::interprocess::open_or_create, unit_tests_constants::shm_failed_tests_list.c_str(), 10240, 0, perm);

    typedef boost::interprocess::allocator<char, boost::interprocess::managed_shared_memory::segment_manager> CharAllocator;
    typedef boost::interprocess::basic_string<char, std::char_traits<char>, CharAllocator> myShmString;

    CharAllocator charallocator(managed_shm_failed_tests_list.get_segment_manager());

    myShmString mystring(charallocator);
}

The problem is that the parameter failed_test_name is a std::string, and I cannot turn it into a myShmString type in order to allocate it in shared memory.

How could I achieve this?

Thank you very much.


Solution

  • Just use any constructor that copies from an input sequence:

    myShmString mystring(failed_test_name.begin(), failed_test_name.end(), charallocator);