Question

Since I'm on a not-quite-C++11 compiler (VS 11) I'm getting a linker error about prevention of usage of copy ctor a assignment operator. All is dandy but the problem is that I can't put my class in a std::map where key is uin32_t and value is my class. I even tried emplace, but it does not work.

I am thinking about std::moveing a unique_ptr into a map, but would prefer not to redesign a container. So is there any elegant way of doing this (elegant == not like putting a dummy in a map and then placement new on the value memory :)?

Code bits are like this:

std::map<uint32_t, LogFileWriter> m_map;

//declared not defined 
public:

LogFileWriter(const LogFileWriter& other);  // commenting this makes emplace work
Was it helpful?

Solution 2

if ( ! mymap.count(ip)) mymap.emplace(pair<uint32_t, LogFileWriter>(source_ip, LogFileWriter(somestring+ ".log")));

Your call to the constructor of pair tries to copy/move a temporary LogFileWriter into the pair. Passing the pair to emplace can't stop that happening.

You should do mymap.emplace(source_ip, somestring+".log");

OTHER TIPS

std::map is not designed to work with objects which are not copy-constructible. You have two options:

  • use std::shared_ptr<LogFileWriter> instead of LogFileWriter as the map value
  • use boost::ptr_map instead of std::map

If you are managing LogFileWriter objects with shared pointers already, you should use the first solution, otherwise use the second one.

You insert raw pointers into boost::ptr_map and its destructor takes care of calling delete for you when appropriate. Note that the insert method has a different signature (takes the key as the first parameter and a pointer to the value as the second one) and for some opaque reason you must provide the key as a non-const lvalue reference.

The documentation for boost::ptr_map is here: http://www.boost.org/doc/libs/1_55_0/libs/ptr_container/doc/ptr_map.html

You have two options:

  1. Use pointers to your objects. No need to use placement-new. The pointers are copyable, you can even manage the lifetime outside your map, and just store a vector of unique_ptr elsewhere, using raw pointers in your map.
  2. Give your class a move constructor. I don't know if this is possible of course, but it might be.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top