What guarantees does D 'const' provide, compared to C++?

Jonathan M Davis jmdavisProg at gmx.com
Thu Aug 16 19:49:28 PDT 2012


On Friday, August 17, 2012 04:30:42 Mehrdad wrote:
> So unless you're expecting the compiler to have the
> implementation for the entire class available in order for it to
> be able to do any kind of optimization (in which case, it would
> have to do a whole bunch of inference to figure out the aliasing
> issues, which would amount to what a C++ could try do just as
> well), I'm not seeing where the additional guarantees/potential
> optimizations are.

It's probably going to be restricted to primitive types in many cases due to 
not knowing what member functions are doing. But take this code for example:

auto i = new int;
*i = 5;
const c = i;
writeln(c);
func(c); //obviously takes const or it wouldn't compile
writeln(c);

The compiler _knows_ that c is the same before and after the call to func, 
because it knows that no other references to that data can exist. And since 
it's a built-in type, it also knows that there's no way that any functions 
operating on func can wile away any mutable, global references to it. So, if 
we were doing something more interesting than writeln before and after func - 
something which could actually be optimized based on the knowledge that c is 
unchanged - then const alone is enough to guarantee that that optimization is 
valid. The same cannot be said of C++, which could cast away const on c inside 
of func and do who-knows-what to it.

If you use a class instead of int and take it one step further and simply make 
its constructor pure, then the compiler _still_ knows that the object is the 
same before and after the call to func, even if none of the class' other 
functions are pure, because it knows that no mutable references to the data 
can exist beyond i.

Once you're dealing with code which doesn't include the creation of the 
object, it's likely much harder to make any gurantees about it not being 
altered, because the compiler doesn't know whether any other references to the 
data exist or not, and then purity matters that much more, but if the compiler 
knows that no other references to the data exists, then const is enough, even 
if the object is passed to other functions, unlike with C++.

- Jonathan M Davis


More information about the Digitalmars-d mailing list