const?? When and why? This is ugly!

Burton Radons burton.radons at shaw.ca
Fri Mar 6 14:03:38 PST 2009


Andrei Alexandrescu Wrote:

> In D you will be able to break any design with a cast, unless you use 
> the not-yet-defined D2 which disallows all risky casts. So the fact that 
> you can cast const away is hardly changing anything.

Oh, and this is an idea which is almost exactly 20 years old, from back when ANSI was developing the C standard. They had defined const but then made it so that const cannot be casted off, making the language unimplementable.

We cannot avoid these APIs which led to this unimplementability because it's a common problem: a mutable object goes through an environment where it is treated as const, but afterwards needs to continue to be mutable. For example, you might have:

  alias const (char) [] string;
  alias char [] mstring;

  // Return the first match within the string, or null if there is no match.
  string match (string text, RE expression);

  mstring text;

  auto submatch = match (text, expression);
  submatch [] = ' '; // Fails.

The only non-casting alternative is to define:

  mstring mmatch (mstring text, RE expression);

But there are two problems. One, it's the same exact function which does the same exact thing. So you're wasting the programmer's time for moving match into a template function and then overloading it twice, you're wasting the reader's time for having to learn two functions and knowing when to apply either, and you're wasting the processor's time for having to load both functions. More critically, it's not descriptive; it in fact implies that mmatch may or will modify the data within the text, when it won't, ever. So if the purpose is to make const describe the nature of the implementation of the function, it has completely failed and so can't be trusted anywhere.

Dennis Ritchie argued against const when it appeared (http://www.lysator.liu.se/c/dmr-on-noalias.html).



More information about the Digitalmars-d mailing list