const?? When and why? This is ugly!

Burton Radons burton.radons at gmail.com
Sun Mar 8 00:54:03 PST 2009


Walter Bright Wrote:

> Burton Radons wrote:
> > Walter Bright Wrote:
> > 
> >> Burton Radons wrote:
> >>> This wouldn't be too bad because const is worthless when
> >>> optimising, but if invariant is going to be given any weight then
> >>> we must never cause data to be casted to invariant unless if it's
> >>> actually invariant data. So, the sensible default is "const
> >>> (char) []" for strings, a selection of aliases in object.d for
> >>> the others, and safe casting templates in object.d.
> >> What I interpret from this is that you see strings as fundamentally
> >>  mutable character arrays, and sometimes in special cases you can
> >> make them immutable. I propose turning that view on its head -
> >> regard strings as fundamentally immutable, and having a mutable
> >> char array is a rare thing that only appears in isolated places in
> >> the program.
> > 
> > No, I don't. You are misunderstanding me, and I'm not sure why or
> > how.
> 
> I guess I just cannot figure out where you're coming from.
> 
> > Here's a (contrived) example of where my concern may come into
> > play:
> > 
> > int [] a = new int [1];
> > 
> > a [0] = 1;
> > 
> > auto b = cast (invariant (int) []) a;
> > 
> > a [0] += b [0]; a [0] += b [0]; writef ("%s\n", a [0]); // Normal
> > result: 4. // Optimiser which assumes invariant data can't change: 3
> > 
> > Yes, the code is an abuse of the const system. THAT'S EXACTLY MY
> > POINT. Casting mutable data to invariant leads to situations like
> > these. Only data which will never change can be made invariant.
> > Putting "alias invariant (char) [] string" in object.d induces these
> > situations and makes it seem like it's a good idea.
> 
> I'm still not understanding you, because this is a contrived example 
> that I cannot see the point of nor can I see where it would be 
> legitimately used.

Obviously I made it contrived so that it's as clear as possible what the issue is. In reality, it will be going through more layers. Here's one layer:

   int [] a = new int [1];
   a [0] = 1;

   invariant (int) [] func (invariant (int) [] a) { return a; }

   auto b = func (cast (invariant (int) []) a); 

Notice this has the same pattern as std.string.replace; that's why I did that cast.

   a [0] += b [0];
   a [0] += b [0];
   writef ("%s\n", a [0]);
   // Not optimised: 4.
   // Assuming b cannot be modified: 3.

When this actually crops up in bugs the reality will be far more complex and practically impossible to discover.

I think I've stated this warning a half-dozen times in the last three days, and that's it, I'm done.



More information about the Digitalmars-d mailing list