c++boostsetboost-ptr-container

How do I delete from a boost::ptr_set when I know the pointer I inserted?


How do I delete from a boost::ptr_set when I know the pointer I inserted? (I have a this pointer to the inserted class object).

Here is a contrived example to show what I am trying to do:

boost::ptr_set<ServerConnection1> m_srv_conns1;

ServerConnection1 *this_ptr;
m_srv_conns1.insert(this_ptr = new ServerConnection1);
m_srv_conns1.erase(this_ptr); //It won't work!

Having a this pointer to the inserted object, how do I tell the boost::ptr_set to erase(this)? Note: I am no longer within the inserted object, but I have a pointer to it.

Update

One of the comments was that I was not fulfilling all the requirements of boost::ptr_set. What are the requirements?

I think providing a < operator would do the trick?

Answer

  1. Change m_srv_conns1.erase(this_ptr); to m_srv_conns1.erase(*this_ptr);
  2. Put the following code inside the ServerConnection1 class:

bool operator<(const ServerConnection1 & sc1) const
{
return (this < &sc1); //Pointer comparison
}


Solution

  • Try m_srv_conns1.erase(*this_ptr);.