【发布时间】:2010-04-08 00:59:34
【问题描述】:
我有一个 std::list 或 boost::shared_ptr<T>,我想从中删除一个项目,但我只有一个 T* 类型的指针,它与列表中的一个项目匹配。
但是我不能使用 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::find 与自定义比较一起使用,或者循环遍历列表蛮力并自己找到它,但似乎应该有更好的方法。
我是否遗漏了一些明显的东西,或者这太不标准了,无法以干净/正常的方式删除?
【问题讨论】:
标签: c++ stl boost smart-pointers