代码之家  ›  专栏  ›  技术社区  ›  ZioByte

使用`unique_ptr创建`map``

  •  0
  • ZioByte  · 技术社区  · 4 年前

    我最初在创建 map 的课程,在一些帮助下 我意识到我真的需要一个 map<string, unique_ptr<myclass>> .

    更准确地说:

    • 我有一群有共同祖先的专业课。
    • 专门化的类实际上是从同一个模板专门化的。
    • 我有一个 std::map<std::string, unique_ptr<ancestor>> 取得所有权 (我希望)。
    • 我需要所有权,因为创建实例的函数位于 与使用它们的地方完全不同的代码部分。
    • 如果有用:我创建 地图 在初始化时,然后我只 在运行时引用它;用于初始化后的所有实际用途 它(一件复杂的事情,涉及读取配置文件)可能会变成 const .

    我需要实现的一个最简单的例子是:

    #include <iostream>
    #include <string>
    #include <memory>
    #include <map>
    
    class generic {
        std::string _name;
    
    public:
        generic(std::string name) : _name(name) {}
        virtual ~generic() = default;
    
        virtual std::string name() { return _name; }
        virtual std::string value() { return "no value in generic"; }
    };
    
    template <class T> class special : public generic {
        T _value;
    public:
        special(std::string name, T value) : generic(name), _value(value) {}
        virtual ~special() = default;
    
        std::string value() override { return std::to_string(_value); }
    };
    
    template <typename T> void add_item(std::map <std::string, std::unique_ptr<generic>> &m, const std::string &n, const T &v) {
        m[n] = std::make_unique<special<T>>(typeid(v).name(), v);
    }
    
    int
    main() {
        std::map <std::string, std::unique_ptr<generic>> instances;
    
        add_item<int>(instances, "int", 1);
        add_item<bool>(instances, "bool", true);
        add_item<float>(instances, "float", 3.1415);
    
        for (auto i : instances) {
            std::cout << i.first << " -- " << i.second.get()->name() << " -- " << i.second.get()->value() << std::endl;
        }
        return 0;
    }
    

    不幸的是,我似乎错过了一些东西,因为编译轰炸了“错误:使用已删除的函数”。

    有人能帮我解决这个问题吗?

    1 回复  |  直到 4 年前
        1
  •  7
  •   Ted Lyngmo    4 年前

    在这个循环中,您尝试复制 unique_ptr s、 但是 unique_ptr 复制构造函数被删除。

    for (auto i : instances) {
    

    您需要参考它们:

    for (auto& i : instances) {