4

The question is similar with Initialize static std::map with unique_ptr as value . But in my question map should be readonly. so, how can i initilize static const map, where value is std::unique_ptr:

static const std::map<int, std::unique_ptr<MyClass>> 

In this case initialization inside static function doesn't work,

std::map<int, std::unique_ptr<MyClass>> init()
{
    std::map<int, std::unique_ptr<MyClass>> mp;
    mp[0] = std::make_unique<MyClass>();
    mp[1] = std::make_unique<MyClass>();
    //...etc
    return mp;
}

Initilization via initilization list doesn't work as well

    const std::map<int, std::unique_ptr<MyClass>> = {
        { 0, std::make_unique<MyClass>() }
Vasliy
  • 138
  • 8
  • Did you try `const std::map> mp = {...}`? – felix Mar 29 '19 at 14:36
  • First, what is the specific compilation error you are getting? Second, please provide motivation for your static const map. It seems like there would be a much easier way to accomplish your requirements this using other design patterns. Also, given @felix 's comment, I think you have a typo with your description of "Initialization via initialization list...". – jhill515 Mar 29 '19 at 14:36
  • The initialization list requires copy construction, so doesn't work with unique pointers. Known issue on SO. – Matthieu Brucher Mar 29 '19 at 14:44
  • Possible duplicate of [How to uniform initialize map of unique\_ptr?](https://stackoverflow.com/questions/17180673/how-to-uniform-initialize-map-of-unique-ptr) – Matthieu Brucher Mar 29 '19 at 14:45

1 Answers1

5

You cannot directly instantiate a const map with initializer list of std::unique_ptr because:

constructing from std::initializer-list copies its contents.

and you cannot copy std::unique_ptr.


Therefore, you can "dynamically" create the map (inside a function) and move the content into a const map.

That is:

using Map = std::map<int, std::unique_ptr<int>>;

static Map GenMap() {
  Map m;
  m[0] = std::make_unique<int>(0);
  // ...
  return m;
}

static const Map globalStaticMap = GenMap();

Lambda can avoid defining the static function making your code more compact.

static const Map globalStaticMap = []() {
  Map m;
  m[0] = std::make_unique<int>(0);
  // ...
  return m;
}();
BiagioF
  • 9,368
  • 2
  • 26
  • 50