Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allocate a non-copyable and non-movable object into std::map?

I have an object that I want to restrict to be allocated only inside of a std::map. Here is the simplified code:

#include <map>

class Value
{
public:
    Value(int value) { _value = value;}
    Value(const Value&) = delete;
    Value& operator=(const Value&) = delete;
    Value(Value&&) = default;     // ***
    void* operator new(size_t) = delete;    // not on free store
private:
    int _value;
};

class Container
{    
public:
    Container();
    Value* addToMap(int key) {
        auto ret = _map.emplace(key, key);
        return &(ret.first->second);
    }
private:
    std::map<int, Value> _map;
};

In order to make it compile on Mac using CLang I had to add a line marked by asterisks requesting default move constructor. However this line causes C2610 error when compiled in Windows Visual Studio. Looks like VS2013 C++11 non-compliance includes inability to generate default move constructors. Is there a different way for me to allocate an object inside of standard map that would compile across platforms or do I have to implement my own move constructor?

like image 847
LRaiz Avatar asked Oct 13 '14 14:10

LRaiz


1 Answers

An option is to use std::piecewise_construct:

Value* addToMap(int key) {
    auto ret = _map.emplace(std::piecewise_construct
                          , std::forward_as_tuple(key)
                          , std::forward_as_tuple(key));
    return &(ret.first->second);
}

VC++ DEMO

like image 59
Piotr Skotnicki Avatar answered Oct 20 '22 08:10

Piotr Skotnicki