如何访问 boost::interprocess 中的共享集?

How do I access a shared set in boost::interprocess?

下面的代码有什么问题?我正在尝试创建一个共享集并向其中添加一些字符串。编译器抛出一个非常冗长的错误,这超出了我对 c++ 的有限理解,更不用说提升了。


//g++ test.cpp -lboost_thread -lrt -lpthread

#include <boost/interprocess/containers/set.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <iostream>
#include <vector>
#include <unordered_map>

using namespace boost::interprocess;

typedef boost::interprocess::allocator<char, managed_shared_memory::segment_manager> CharAllocator;
typedef boost::interprocess::basic_string<char, std::char_traits<char>, CharAllocator> SHM_String;
typedef boost::interprocess::allocator<SHM_String, managed_shared_memory::segment_manager> StringAllocator;
typedef boost::interprocess::set<SHM_String, StringAllocator> SHM_StringSet;
typedef allocator<SHM_StringSet, managed_shared_memory::segment_manager> ShmemAllocator;

offset_ptr<SHM_StringSet> create_stringset_and_add_ten_strings(managed_shared_memory* segment, 
            CharAllocator* ca, 
            std::string name,
            std::string arr[10]) {
    ShmemAllocator alloc_inst (segment->get_segment_manager());
    offset_ptr<SHM_StringSet> m_pset = segment->construct<SHM_StringSet>(name.c_str())(alloc_inst);

    for (int i = 0; i < 10; i++) {
        SHM_String mystringFirst(*ca);   
        mystringFirst = arr[i].c_str();
        m_pset->insert(mystringFirst);
    }

    return m_pset;
}

int main ()
{

    shared_memory_object::remove("SharedMemoryName");
    managed_shared_memory segment(create_only,"SharedMemoryName",65536);
    
    CharAllocator charallocator(segment.get_segment_manager());
    std::string xnames[10] = { "car", "bike", "truck", "bus", "bicycle", "car", "bike", "truck", "bus", "bicycle" }; 
    create_stringset_and_add_ten_strings(&segment, &charallocator, "vehicles",  xnames);

    return 0;
}

错误基本上是说

usr/include/boost/container/detail/tree.hpp:468:30: error: no match for call to ‘(const key_compare {aka const boost::interprocess::allocator<boost::container::basic_string<char, std::char_traits<char>, boost::interprocess::allocator<char, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >}) (const key_type&, const key_type&)’
  468 |    {  return this->key_comp()(this->key_from(nonkey1), key2);  }

注意 set 的定义是:

template <class Key
         ,class Compare  = std::less<Key>
         ,class Allocator = void
         ,class Options = void>
class set;

因此,据此,如果您以这种方式更改 SHM_StringSet typedef,编译步骤将通过:

typedef boost::interprocess::set<SHM_String, std::less<>, StringAllocator> SHM_StringSet;