Vasliy
Vasliy

Reputation: 138

Initialize const static std::map with unique_ptr as value

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>() }

Upvotes: 4

Views: 826

Answers (1)

BiagioF
BiagioF

Reputation: 9735

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;
}();

Upvotes: 6

Related Questions