C++ Annoyances

03 May 2006

Just one C++ annoyance actually. Having the ability to create an object on the stack complicates memory management a bit. I’ve got all my objects derived from this base class that provides reference counting for memory management. So I’ve got this decision now: should an initially created object have 0 or 1 references? I’m of the opinion that it should have one, because something obviously created it, so it’s holding a reference to it.

For debugging and safety’s sake, I throw an assert in the base class’ destructor that will fire if the object is freed with any references left. Nice for debugging, but it doesn’t work if I create a base-derived object on the stack. If I do, it’ll be created with one reference and be automatically destroyed as soon as the function ends, firing off the assert. I can’t just call release() on the object, ‘cause release() will try and free the object because its ref-count will drop to 0, but it can’t do that for an object created on the stack.

I like Objective-C and Java’s approach here better: you can’t create an object on the stack. You have to explicity allocate the thing, no magic.

I prefer Objective-C over C++ in general, but the lack of good tools outside of OS X have been keeping me from using it. I’m addicted to Visual Studio. :)

As an aside, I do understand that being able to create objects on the stack in C++ is what makes Resource Acquisition As Initialization (did I get that right?) work, but that’s really just a workaround for not having garbage collection anyway. Not that Objective-C has garbage collection (natively), but the omnipresent reference counting and autorelease pools do a good job of hiding it.