What's correct way to remove a boost::shared_ptr from a list?

Posted by Catskul on Stack Overflow See other posts from Stack Overflow or by Catskul
Published on 2010-04-08T00:59:34Z Indexed on 2010/04/08 1:03 UTC
Read the original article Hit count: 359

Filed under:
|
|
|

I have a std::list of boost::shared_ptr<T> and I want to remove an item from it but I only have a pointer of type T* which matches one of the items in the list.

However I cant use myList.remove( tPtr ) I'm guessing because shared_ptr does not implement == for its template argument type.

My immediate thought was to try myList.remove( shared_ptr<T>(tPtr) ) which is syntactically correct but it will crash from a double delete since the temporary shared_ptr has a separate 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
}  

The only options I see remaining are to use std::find with a custom compare, or to loop through the list brute force and find it myself, but it seems there should be a better way.

Am I missing something obvious, or is this just too non-standard a use to be doing a remove the clean/normal way?

© Stack Overflow or respective owner

Related posts about stl

Related posts about boost