What if D would require * for reference types?

Denis Koroskin 2korden at gmail.com
Mon Jan 18 07:10:00 PST 2010


(I moved that part to a different letter so that people don't concentrate  
on it too much, since it is more controvertial)

What else would it *optionally* provide (subject to discuss, could be  
implemented later, because it's an additional functionality that D  
currently lacks)?

I stress it one more time: it's *OPTIONAL*, but it keeps getting asked for  
and this proposal allows the feature quite nicely IMO.

1) Allow constructing classes on stack and get rid of "scope Foo" hack (it  
doesn't even work well: "scope Foo = createFoo();" <- heap-allocates,  
scope is noop here)
Consistent with structs

2) Allow class aggregation without additional allocation cost (no need for  
InSitu, which is not implementable in current D anyway):

class Foo
{
}

struct Bar
{
     Foo foo; // < analog of InSitu!(Foo)
}

Consistent with structs.

3) Returning class instances from functions via stack:

Foo createFoo()
{
    Foo foo; // default ctor is called
    // initialize
    return foo;
}

Foo foo = createFoo(); // created on stack

Consistent with structs.

4) Class array allocation:

Foo* foo = new Foo[42]; // allocates Foo.sizeof*42 bytes and calls default  
ctor on each object
(*Not* consistent with structs, until struct default ctors will be allowed)

5) Safe class instance assignment:

Foo foo1;
Foo foo2;
foo1 = foo2; // okay, consistent with classes

6) Slicing prevention rules:

class Bar : Foo {}

Bar bar;
foo1 = bar; // error, assigment from different type

Foo* fooPtr = new Bar();
foo1 = *fooPtr; // error, class pointer dereference not allowed

What do you think? I understand it is unlikely to make its way into D2  
(D3?), but is it sound? Do you think it's useless, or do you think that  
additional consistency (and functionality) is worthwhile?



More information about the Digitalmars-d mailing list