将unique_ptr插入到map中,指针会被销毁

时间:2012-05-14 08:39:02

标签: c++ c++11 stdmap unique-ptr

我正在使用以下(简化)课程:

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()的末尾调用。

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

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

修改#2 :在输入setOperandsValue并执行op.find(o)后,结果为op.end,即虽然我之前已添加,但未找到条目。< / p>

1 个答案:

答案 0 :(得分:3)

我认为你的指针没有被破坏。你在这看到的是什么:

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的破坏,用于构造T中使用的分配unique_ptr的堆。

地图为空不是指针被销毁的症状。如果是这种情况(指针被销毁),您将在地图中为给定密钥创建一个条目,其中包含无效的unique_ptr。