3

I have this MCVE:

#include <atomic>
#include <map>
#include <string>

struct foo
{
    int intValue;
    std::atomic_bool bar;

    foo( int intValue ) : intValue( intValue ) {};
};

std::map<std::string, foo> myMap;

int main()
{
    myMap.emplace( "0",  1234 );
}

It does not compile because std::atomic is neither copyable nor movable.

My question:

How can I add a class containing a not copyable/moveable object to a std::map container?

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
Peter VARGA
  • 4,780
  • 3
  • 39
  • 75
  • You really should not use `const char*` as a key to a mapping. That's because it will be the *pointer* that is the key, not what it points to. – Some programmer dude Sep 04 '16 at 00:44
  • @JoachimPileborg: This is an `MCVE`. In my real project it is `std::string` and `foo` is much more complicated. I wanted to make it really very small. Thx – Peter VARGA Sep 04 '16 at 00:45
  • For future reference, when creating a MCVE, please don't add possible other sources of errors, as that will only confuse us. Actually *create* an MCVE, as close to your actual program as possible. – Some programmer dude Sep 04 '16 at 00:48

1 Answers1

3

What about

myMap.emplace(std::piecewise_construct,
              std::forward_as_tuple("0"),
              std::forward_as_tuple(1234));

?

max66
  • 65,235
  • 10
  • 71
  • 111
  • 1
    @AlBundy You'd have heard about it if you'd _read_ and _studied_ the documentation for `std::map` as part of planning for this task... – Lightness Races in Orbit Sep 04 '16 at 01:08
  • @LightnessRacesinOrbit [http://en.cppreference.com/w/cpp/container/map/emplace](http://en.cppreference.com/w/cpp/container/map/emplace) has the example but - this I checked first due to Google sort order - [http://www.cplusplus.com/reference/map/map/emplace/](http://www.cplusplus.com/reference/map/map/emplace/) does **not**. – Peter VARGA Sep 04 '16 at 01:44
  • 4
    @LightnessRacesinOrbit no need for such comments imho – M.M Sep 04 '16 at 07:50
  • @M.M: Teach a man to fish, mate. It's the single most helpful thing you'll do all day. Thanks for your constructive contribution to this thread, though (can't believe you came here _just_ to say that - no need for such comments imho) – Lightness Races in Orbit Sep 04 '16 at 13:35