使用unique_ptr作为值初始化静态std :: map [英] Initialize static std::map with unique_ptr as value

查看:310
本文介绍了使用unique_ptr作为值初始化静态std :: map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何初始化值为 std :: unique_ptr 的静态地图?

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

static void f()
{
    static std::map<int, std::unique_ptr<MyClass>> = {
        { 0, std::make_unique<MyClass>() }
    };
}

当然这不起作用( std :: unique_ptr 被删除)。

Of course this does not work (copy-ctor of std::unique_ptr is deleted).

有可能吗?

推荐答案

问题是从 std :: initializer-list 复制其内容。 ( std :: initializer_list 中的对象本质上是 const )。
要解决您的问题:可以从单独的函数初始化地图...

The Problem is that constructing from std::initializer-list copies its contents. (objects in std::initializer_list are inherently const). To solve your problem: You can initialize the map from a separate function...

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

然后称呼它

static void f()
{
    static std::map<int, std::unique_ptr<MyClass>> mp = init();
}

查看它在Coliru上直播

这篇关于使用unique_ptr作为值初始化静态std :: map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆