Const-correctness
One of my fellow lab-mates has already posted about const-correctness, because of some similar issues. My work today, takes it a tiny bit further into sheer insanity.
If you don’t start your program off using a const-correctness discipline, it’s very likely that you will find yourself in a world of hurt when you try to add it in later. I hit something like this today. In our system we have these labels, which are managed by a Factory and which are supposed to be immutable. Because all the labels are managed by a factory, we have a whole bunch of pointers:
JSFlowLabel *lab = ... |
Although no bugs have come up as a result, we should have decided a long time ago, to enforce the immutable semantics with the compiler. So, after seeing a few suspicious lines today, (which turned out to be fine, but which raised my paranoia alarms) I decided that we should add const. Beginning with the Factory that produces these:
JSFlowLabel const* JSFlowLabel::create(...) {...} |
Followed by a hundred changes to code like the above, and a few method call modifications.
JSFlowLabel const *lab = ... JSFlowLabel::join(JSFlowLabel const *lab1, JSFlowLabel const *lab2) {...} |
But, of course, just when you think you are nearing completion, there’s some line lurking somewhere to bite you.
js::Value val = ... JSFlowLabel const *lab = ... val.setPrivate(lab); |
And what, pray tell, is the signature of setPrivate(...)
?
void setPrivate(void *data); |
Oh, well that’s easy to fix, I think to myself. I’ll just overload a const
version and dispatch.
void setPrivate(void const *data) { setPrivate(const_cast<void *>(data)); } |
Having got this far, I still have some hope things will work out. I start the compiler to test my changes, and wonder a bit about what deep ruminations about data have led the compiler to draw such a sharp philosophical distinction between void
and const void
. And despite these wonderful distinctions, I’m still never allowed to make data of type void
, only functions that can return a void
whatever that means, … wait, can I have a function returning a const void
? If I continue this line of thought, will I become as useless as a philosopher? Does enough rumination about void
type your thoughts as void
? Is the brain-rot setting in? Will I ever be able to recover the damage C++ has caused me?. Oh, yeah, back to my story…
So, I was thinking things might work themselves out, and (at worst) I’d have to make a few more wrapper overloads to some system-level functions. But NO! my very sanity was soon challenged by the compiler:
../jsfun.cpp:1158: error: call of overloaded ‘setPrivate(NULL)’ is ambiguous ../jsobj.h:742: note: candidates are: void JSObject::setPrivate(void*) ../jsobj.h:747: note: void JSObject::setPrivate(const void*)
At this point my all my thoughts were dumped to /dev/null
. The C++ typing system is clearly more depraved than I am, so it wins this round!