1

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
}

unixman83
  • 9,421
  • 10
  • 68
  • 102
  • `m_srv_conns1.erase(m_srv_conns1.find(this_ptr))`? I don't really know how `boost::ptr_xxx` work, but that's how it would look like for a normal `std::set`. Or maybe just save the iterator from the `pair` returned by `insert`. – Xeo Dec 28 '11 at 12:44

1 Answers1

0

Try m_srv_conns1.erase(*this_ptr);.

wilx
  • 17,697
  • 6
  • 59
  • 114
  • That gives me about a 1000 character error messages that I don't care to sort through :( – unixman83 Dec 28 '11 at 12:37
  • 1
    Read the docs at http://www.boost.org/doc/libs/1_48_0/libs/ptr_container/doc/associative_ptr_container.html. I think that you are not satisfying all the requirements for the elements of `boost::ptr_set<>`. – wilx Dec 28 '11 at 12:44
  • updated question, what are the requirements of boost::ptr_set<>? – unixman83 Dec 28 '11 at 12:48
  • They mention the Clonable concept: http://www.boost.org/doc/libs/1_48_0/libs/ptr_container/doc/reference.html#the-clonable-concept. The problem is likely visible from the error message that you do not care to analyze. – wilx Dec 28 '11 at 12:54
  • 1
    Add `operator <` might do or you could just provide own *less than* functor as second parameter to the `boost::ptr_set<>`. – wilx Dec 28 '11 at 13:02