Casting const/invariant
Jason House
jason.james.house at gmail.com
Wed Jan 2 15:27:28 PST 2008
I don't know about others, but it looks to me like the community has come close to accepting D's const design. I know it's probably the last thing anyone wants to hear, but below are my thoughts on extending the design.
Right now, the docs say "[When casting data to invariant] it is up to the programmer to ensure that no other mutable references to the same data exist. "
Const is useful for interface guarantees, but does not allow the compiler to optimize code like it can with invariant data. Unlike const, the compiler will be unwilling to (silently) cast data to invariant. For invariant data to be useful, I think there needs to be a way for casting to be safe.
I think the key is adding a concept of exclusive write access to data. For the sake of this post, I'll call data with exclusive write access "exclusive" and those that don't have it "shared". Just to confuse everyone, I'll use "readonly" instead of const in my discussion...
Note that with this notation,
invariant = exclusive readonly
const = shared readonly
shared data gives behavior exactly like everyone currently expects. You never know who has a mutable reference to the data, and the compiler gives no guarantees to that fact.
exclusive data can be implicitly cast to scope invariant for function calls. This would allow a function with const parameter signature to use a version optimized for invariant access.
I would suggest that member/global variables default to shared access and local variables (in functions) default to exclusive access. Using the variables as "in" parameters or "scope ref" parameters would require no modification. Using them inside delegates or passing to non-scope "ref" parameters would require the data be shared.
Function return types and out parameters to functions are the stickiest part. By default, they'd have to be shared access, but for this scheme to really be worthwhile, some framework for specifying when these outputs can be used as exclusive access (AKA the function leaves no mutable references in any other locations)
Thoughts?
More information about the Digitalmars-d
mailing list