将unique_ptr插入地图,指针被销毁

Insert unique_ptr into map, pointer gets destroyed

本文关键字:指针 地图 unique ptr 插入      更新时间:2023-10-16

我有以下(简化)类:

class Operator {
private:
    std::map<std::string, std::unique_ptr<Operand>> op;
public:
    template <class T>
    void insertOperand(std::string const &s, T o = T()) {
        op.insert(std::pair<std::string, std::unique_ptr<StreamOperand>>(
            s, std::move(std::unique_ptr<T>(new T(o)))
        );
    }
    void setOperandsValue(std::string const &o, int v) {
        op.find(o)->second->setValue(v);
    }
};

插入新Operand没有任何问题。但是,当函数返回时,析构函数被调用,因此map在调用setOperandsValue时不包含任何对象。我已经使用 DDD 观察到了这一点:在 insertOperand Operator::~Operator() 结束时被调用。

在看了在STL中使用std::unique_ptr之后,我介绍了(更好:使用)std::move但要么它没有正确放置,要么我错过了一些东西(很可能由于缺乏知识)。我没有使用map::emplace,因为它不可用。

编辑:析构函数调用有效,因为它正在销毁new T(o)。无论如何,map在输入setOperandsValue时保持为空。

编辑#2:在输入setOperandsValue并执行op.find(o)时,结果是op.end,即尽管我之前已添加过,但找不到条目。

我不认为你的指针被破坏了。你在这里看到的:

template <class T>
void insertOperand(std::string &s, T o = T()) {
    op.insert(std::pair<std::string, std::unique_ptr<StreamOperand>>(
        s, std::move(std::unique_ptr<T>(new T(o)))
    );
}

o的破坏,在它被用来构造unique_ptr中分配T使用的堆之后。

地图为空并不是指针被破坏的症状。如果是这种情况(指针被销毁),您将在映射中有一个给定键的条目,并带有无效unique_ptr。