Array type conversion

James Dennett jdennett at acm.org
Sat Apr 28 15:10:23 PDT 2007


Walter Bright wrote:
> Mark Burnett wrote:
>> Certainly making a copy prevents this problem, but what I'm really
>> curious about is the motivation for including these imlicit
>> conversions (they are mentioned specifically on the Array description
>> page on digitalmars.com).
>>
>> They're not safe in general,
> 
> Why not?
> 
>> so I imainge library designers will end up using their own
>> user-defined array/vector type just as in c++, so that such errors are
>> caught at compile time.  This seems to limit the usefulness of these
>> built in array types.  Sure they're bounds-safe, but they don't seem
>> 100% type-safe.
>>
>> For example:
>>
>> std::vector<derived> ad;
>> std::vector<base> ab;
>>
>> ab = ad; // c++ compiler error
>>
>> A compiler error is more what I would expect.  Treating a container of
>> derived as a container of base is an error.
> 
> But that isn't what is happening with D. base[] is an array of
> *references* to base, so the slicing problem one has in C++ is not
> possible in D.

Slicing isn't the big issue.  The big issue is semantics;
an array of derived is not an array of base, by LSP.

An array of (pointers/references to) derived is usable
as an *immutable* array of base (for suitable English
meaning of immutable, matching C++'s notion of the
array (equivalently, the pointers it contains) being
const.

Java has runtime checks required because it allows
conversion from array of Derived to array of Base,
and that (as you know) also uses reference semantics.
The conversion is widely viewed as a mistake in Java;
if I pass a Derived[] around, the language should
not silently allow one of its elements to refer to
a Base object.

-- James



More information about the Digitalmars-d mailing list