const challenge

Steven Schveighoffer schveiguy at yahoo.com
Mon Feb 4 06:43:27 PST 2008


"Walter Bright" wrote
> Oskar Linde wrote:
>> I can't help but agree. The very first thing I tried when D 2.009 was 
>> released was:
>>
>> struct Vector { int x,y; }
>> invariant Vector up = {0,1};
>> void main() {
>>     Vector y = up;
>> }
>>
>> which didn't work because:
>>     Error: no property 'opCall' for type 'Vector'
>> ??? No idea what that means. Is it trying to implicitly call a 
>> non-existant struct static opCall "constructor"?
>
> The issue here is assigning a mutable instance of Vector to an invariant. 
> If Vector contained a pointer, then there's a big correctness hole. So 
> then the issue is "since Vector does not contain any pointers, shouldn't 
> this work?" The problem then is that if one builds code that uses Vector 
> in this manner, and later the maintainer adds a pointer member variable to 
> Vector, then all those uses of Vector break.

I just wanted to respond to this one point.

I think it is unreasonable for the compiler to restrict code from compiling 
because someone might change an API or implementation in the future.  It is 
always possible to break code in the future by changing an API or type.  Why 
should a developer who is certain that the type will never contain a pointer 
be punished because the compiler can't predict what he will do with the type 
in the future?  What if someone does add a pointer to vector, then other 
pieces of code that expect copying a vector to make a 'deep copy' will 
break.  I understand the concern, but I just don't think your argument is 
valid.  Also, having this restriction makes it impossible to mimic builtin 
types with struct wrappers, as builtin types already enjoy this benefit.

The real question is, is it possible for the compiler to determine whether a 
type contains pointers, and if so, restrict copying const or invariant 
versions of the type to mutable types.  I believe the answer is yes, 
although the compiler doesn't take that into account today.  I even think 
that it is strictly a compile-time check and therefore should not affect any 
existing code.

If this is the case, the next question is, why would it be undesirable to 
have this behavior?  I have not yet seen a good answer to this.

-Steve 





More information about the Digitalmars-d mailing list