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

Jonathan M Davis jmdavisProg at gmx.com
Thu Aug 16 21:16:46 PDT 2012


On Friday, August 17, 2012 05:11:49 Mehrdad wrote:
> On Friday, 17 August 2012 at 02:49:45 UTC, Jonathan M Davis wrote:
> > 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.
> 
> Is there any reason why your example didn't just say
> 
> > const(int*) c = null;
> > writeln(c);
> > func(c);
> > writeln(c);
> 
> i.e. What was the point of 'i' there?
> And why can't a C++ compiler do the same thing?
> 'c' is a const object, so if C++ code was to modify it, it would
> be undefined behavior, just like in D.
> Sorry, I'm a little confused at what you were illustrating here.

1. Because it wasn't creating as const, C++ could legally mutate the object in 
func by casting away const (meaning that it can't assume that c is unchanged 
after the call to func), which is not the case in D. But if it were created as 
const, then it would undefined behavior in both languages.

2. If you want to assign an actual value to c rather than null, you either 
need to use a helper function or create a mutable one first, because there's no 
do something like

const int* c = new int(5);

and have c point to an int with value 5.

So, with my example, the D code can guarantee that func doesn't modify either 
c or what's pointed to by c, whereas C++ provides no such guarantee. So, any 
optimizations which could be done based on the fact that func didn't change 
C's value can be done in D but not C++.

- Jonathan M Davis


More information about the Digitalmars-d mailing list