Re: What kind of pattern is this?
On Nov 9, 8:54 pm, Marcel M=FCller <news.5.ma...@spamgourmet.org> wrote:
I have a class that destroys itself after it has done its job. Something
like a thread, but without a thread.
// Some Object
class MyObject;
// Schedule a task for obj in the Worker Queue.
void ScheduleObject(MyObject* obj);
class RescheduleWorker
{private:
intrusive_ptr<MyObject> Object;
vector<intrusive_ptr<MyObject> > Dependencies;
public:
RescheduleWorker(MyObject& obj,
const vector<intrusive_ptr<MyObject> >& dependencies)
: Object(&obj), Dependencies(dependencies)
{ // register some callbacks in the dependency list
}
private:
~RescheduleWorker() {}
// Called by some internal observer functions exactly once
// when a complex dependency condition is true.
void OnCompleted()
{ ScheduleObject(Object.get());
delete this;
}
};
// usage:
new RescheduleWorker(obj, dependencies);
The latter looks a bit strange, because the pointer returned by new is
immediately discarded. Is this a common pattern? How is it called?
"delete this" is seen in places, and, beside intrusive refcounting, I
am yet to see a reason why it is a good idea. In your case, ownership
of the object is effectively taken by whoever is going to call
OnCompleted. So that somebody can do
p->OnCompleted();
delete p;
or better yet
auto_ptr<ReshceduleWorker>(p)->OnCompleted();
and "delete this" should disappear.
"delete this" is usually a sign of underdesigned heap object
ownership.
Goran.