我有一个std::list
的boost::shared_ptr<T>
,我想从中删除一个项目,但我只有一个T *类型的指针,它与列表中的某个项目相匹配。从列表中删除boost :: shared_ptr的正确方法是什么?
但是我不能使用myList.remove(tPtr)
我猜测是因为shared_ptr没有为其模板参数类型实现==
。
我的直接想法是尝试myList.remove(shared_ptr<T>(tPtr))
它在语法上是正确的,但它会从双删除崩溃,因为临时shared_ptr
有一个单独的use_count。
std::list< boost::shared_ptr<T> > myList;
T* tThisPtr = new T(); // This is wrong; only done for example code.
// stand-in for actual code in T using
// T's actual "this" pointer from within T
{
boost::shared_ptr<T> toAdd(tThisPtr); // typically would be new T()
myList.push_back(toAdd);
}
{
//T has pointer to myList so that upon a certain action,
// it will remove itself romt the list
//myList.remove(tThisPtr); //doesn't compile
myList.remove(boost::shared_ptr<T>(tThisPtr)); // compiles, but causes
// double delete
}
我看到剩下的唯一选择是使用std ::找到通过列表强力的自定义比较,或循环并找到它自己,但它似乎应该有一个更好的办法。
我是否错过了一些明显的东西,或者这太不合标准了吗?
+1为最直接的解决问题。 – 2010-04-08 01:51:48