I have an .hpp
looking similar to this
#include <boost/intrusive/list.hpp>
#include <unordered_map>
using namespace boost::intrusive;
struct Tag;
using Hook = list_base_hook< tag<Tag> >;
class Str : public Hook
{
public:
Str(int n) : n_(n) {}
Str(const Str& s) : n_(s.n_) {}
int n_;
};
using List = list< Str, cache_last<true>, base_hook<Hook> >;
using Map = std::unordered_map<std::string, List>;
and I have 2 threads that are using Map
, a writer and reader, but I can’t lock the writer thread for long, thus I need to create a deep copy of Map
for the reading thread to work on. My problem with that is that intrusive list is movable but not copy-able so I tried to create the list dynamically like so
int deep_copy_map(Map& orig, Map& copy)
{
for (auto& it: orig) {
List list_copy;
for (auto& it1: it.second) {
list_copy.push_back(*(new Str{it1}));
}
copy.insert({ it.first, std::move(list_copy) });
}
}
but now I’m leaking Str
objects as the intrusive list doesn’t destroy its elements. So I next tried to add this to my .hpp
class List_ : public List
{
public:
~List_()
{
while (!this->empty())
{
Str* node = &this->front();
this->pop_front();
delete node;
}
}
};
using Map = std::unordered_map<std::string, List_>;
and update the copy to
int deep_copy_map(Map& orig, Map& copy)
{
for (auto& it: orig) {
List_ list_copy;
for (auto& it1: it.second) {
list_copy.push_back(*(new Str{it1}));
}
copy.insert({ it.first, std::move(list_copy) });
}
}
but now I get the error
error: no matching function for call to ‘std::unordered_map<std::__cxx11::basic_string<char>, List_>::insert(<brace-enclosed initializer list>)’
copy.insert({ it.first, std::move(list_copy) });
Is there a way to create a deep copy of Map
without leaking memory?
I have limited access to the reader thread code, and I’m only allowed to make changes there if they are absolutely necessary