我有以下(简化)类:
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,即找不到条目,虽然我之前已经添加了它。