Extended Type Design: further examples
Andrei Alexandrescu (See Website For Email)
SeeWebsiteForEmail at erdani.org
Mon Mar 19 16:30:10 PDT 2007
Sean Kelly wrote:
> Andrei Alexandrescu (See Website For Email) wrote:
>>
>> By the way, a couple of days ago I've had an idea. Many people here ask
>> for a "string" alias because char[] is a tad hard to type and uneasy on
>> the eyes. Probably a good candidate would be:
>>
>> alias invariant char[] string;
>>
>> The resulting type is pretty damn slick:
> ...
>> 3. The ~= operator works (somewhat surprisingly).
>
> I assume this is because a char[] is actually a struct containing a
> pointer, so 'invariant' allows that pointer to be reassigned--it simply
> protects the referenced string? This is the sticking point for me.
That is correct. For an understanding of a ~= b, think of it as a = a ~
b. Do I modify the stuff indirectly referenced by "a"? No, Sir. I just
rebind a to a larger entity that embeds a copy of its former self.
In practice, the concatenation will not always produce a copy. The
implementation will work "as if" you always produce a copy.
> Assume we have this:
>
> struct Foo
> {
> int x;
> int* y;
> }
>
> const Foo foo; // is this legal?
Yes.
> foo.x = 1; // this is allowed
Yes.
> *foo.y = 2; // this is not allowed
It's not allowed.
> Is that correct, or do 'const' and 'invariant' truly only apply to pure
> reference types?
No. They apply to any type that embeds references.
"final" applies to all types and guards the bits of the symbol itself.
"final const" guards symbol bits + referenced bits, and "final
invariant" is as opposed to change as the 19th century British education
system. (Did I get that right?)
>> 4. It's very, very rare that you want to modify some random character in
>> a string, and when you do, use a char[] and then copy it back into a
>> string, or rebuild the string from slices!
>
> This may be true for a string, but for arrays in general I think this is
> fairly common.
Yes. That's why arrays will stay in place :o).
Andrei
More information about the Digitalmars-d
mailing list