将unique_ptr插入地图,指针被销毁
Insert unique_ptr into map, pointer gets destroyed
我有以下(简化)类:
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。
相关文章:
- 从矢量或地图中删除共享指针
- 如何将元素插入到标准::地图的共享指针中?
- 无法将智能指针插入地图
- 从地图复制到指针列表
- EIGEN地图类:将C阵列映射到VectorXD指针以有效的方式
- 如何在地图中使用结构指针
- 为什么通用参考概念不适用于函数指针的地图插入
- C 通过指针的地图进行迭代
- 从地图擦除后访问指针
- C 如何在地图指针中的键增量值
- std ::地图没有父母指针
- 如何在两个包含指针的地图中创建列表
- 如何将模板函数指针作为值参数添加到地图中
- 使用地图模板函数指针
- 在Unorderd地图中删除指针
- 通过EMPLEPE()将对象指针插入地图中
- 如何在具有非常量指针键的地图中通过常量指针键查找
- 如何通过向量/地图对对象使用多个指针
- 分割故障,可能的原因:功能指针,多线程,STL地图等
- 如何从地图返回标准::p空气的指针并将其放入vector<*std::p air...>