Thursday, October 30, 2008

Const Fail

I only recently discovered an oddity in the C++ "const" feature. Consider this code:
class Foo
{
int *i;

void foo(void) const
{
*i = 4;
}
};
(I've left out some boiler plate)

Anyone see it? A const function is changing the state of the object!

Oops, turns out C++ const is not "transitive" (the D docs call it "head const").

This bit me big time on my previous project. To the point that I developed a "const pointer" class to wrap all my pointers (only got partially deployed into the project).

D 1.0 lacks const (because it is hard to get right, witness C++). D 2.0 wants const done right.

Also, there is a great slam on Java and const. (I can't help myself when it comes to slams on Java! :) Yea, no const for you Java-kins!

No comments: