Friday, February 13, 2009

Hoops to Jump Through

Whose idea was it for C++ classes that have virtual functions to not automatically have a virtual destructor? There is just no reason for this not to be the case. Not having a virtual destructor is just not going to ever do that right thing when you're dealing with a polymorphic class. Most of the time it's probably going to be a silent problem that you're dealing with. My last encounter with this wonderful bit of the C++ obstacle course resulted in a not insignificant memory leak when I failed to jump through the hoop. I have yet to see a case where it would make sense for a polymorphic class to not a virtual destructor. Sometimes I really do think that C++ is just some colossal joke that Stroustrup is playing on us.


About once a year I end up thinking that using boost::enable_shared_from_this is a good idea. And every time it ends up wasting almost an hour of my time. You see there's a restriction on shared_from_this that disallows its use in the constructor of the object that is being shared from this. Unfortunately this restriction is not mentioned in the documentation. I always try to use shared_from_this from the constructor and get bad weak pointer errors at run time. I then spend twenty minutes flailing around in the source code trying to figure out what I'm doing wrong until finally a bit of googling brings the not in the constructor restriction out in the open. Once I realize this and start trying to fix things so I don't need to use shared_from_this in the constructor I find that I don't need enable_shared_from_this at all. This happens every time. I'm guessing that most of the boost folks have had the same experience as well since they don't go out of their way to call attention to enable_shared_from_this. Maybe I should stay away from libraries whose documentation can only be reached from a link in an answer to a FAQ about another library. That is just not a good sign.

Update 3-11-09: Of course now that I've posted this I've had two occasions where boost::enable_shared_from_this turned out to be useful.