Re: Problem with a collection of event sinks
"John" <John@discussions.microsoft.com> wrote in message
template <class T>
class CObjEventSink : public IDispEventImpl<0, CObjEventSink,
&DIID__IEventSink, &LIBID_someLib, 1, 0>
In the main objects header file I define two vectors, one for the
objects and another for the event sinks.
// define a collection of objects and event sinks
std::vector< CObjEventSink <CSomeObj> > m_vecObjSinks;
This is a bad idea. std::vector is going to create and destroy copies of
CObjEventSink at will. E.g. vector sometimes needs to expand, at which
point it allocates new memory block, makes a copy of every object it
holds into this block, destoys all old copies, and frees old memory
Now, you subscribe an instance of CObjEventSink to listen to events.
Then vector comes along, destroys this instance and creates a copy of
it. This copy is of course not subscribed, and event source is left with
dangling pointer. Next time it fires its event, the best that could
happen is immediate crash.
You need a vector of pointers to CObjEventSink. Pesonally, I'd also make
sink object non-copyable, by declaring a private copy constructor and
assignment operator and never implementing them. Then this problem would
have been caught at compile time.
With best wishes,
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925