Initialize static std::map with unique_ptr as value

前端 未结 3 1020
执笔经年
执笔经年 2021-01-18 06:11

How can one initialize static map, where value is std::unique_ptr?

static void f()
{
    static std::map&         


        
3条回答
  •  情书的邮戳
    2021-01-18 06:37

    another way to do this is to use a lambda. it's the same as using a separate function but puts the map's initialisation closer to the action. In this case I've used a combination of an auto& and decltype to avoid having to name the type of the map, but that's just for fun.

    Note that the argument passed into the lambda is a reference to an object that has not yet been constructed at the point of the call, so we must not reference it in any way. It's only used for type deduction.

    #include 
    #include 
    #include 
    
    struct MyClass {};
    
    
    static auto& f()
    {
      static std::map> mp = [](auto& model)
      {
        auto mp = std::decay_t {};
        mp.emplace(0, std::make_unique());
        mp.emplace(1, std::make_unique());
        return mp;
      }(mp);
      return mp;
    }
    
    int main()
    {
      auto& m = f();
    }
    

    Here's another way. In this case we've passed a temporary into the lambda and relied on copy elision/RVO.

    #include 
    #include 
    #include 
    
    struct MyClass {};
    
    static auto& f()
    {
      static auto mp = [](auto mp)
      {
        mp.emplace(0, std::make_unique());
        mp.emplace(1, std::make_unique());
        return mp;
      }(std::map>{});
      return mp;
    }
    
    int main()
    {
      auto& m = f();
    }
    

    And yet another way, using a lambda capture in a mutable lambda.

    #include 
    #include 
    #include 
    
    struct MyClass {};
    
    static auto& f()
    {
      static auto mp = [mp = std::map>{}]() mutable
      {
        mp.emplace(0, std::make_unique());
        mp.emplace(1, std::make_unique());
        return std::move(mp);
      }();
      return mp;
    }
    
    int main()
    {
      auto& m = f();
    }
    

提交回复
热议问题