简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM