Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize const static std::map with unique_ptr as value

Tags:

c++

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>() }
like image 854
Vasliy Avatar asked Oct 27 '25 08:10

Vasliy


1 Answers

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;
}();
like image 171
BiagioF Avatar answered Oct 28 '25 23:10

BiagioF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!