Why can't we make reference variables?
Namespace
rswhite4 at googlemail.com
Thu Aug 30 01:38:42 PDT 2012
On Thursday, 30 August 2012 at 07:35:34 UTC, Namespace wrote:
>
>> I had totally forgotten what it says in "The book" about
>> struct and class construction. It's basically that all fields
>> are first initialized to either T.init or by using the field's
>> initializer. That means the use of ref inside class or struct
>> would be quite restricted:
>>
>> int globalVal;
>>
>> struct MyStruct
>> {
>> // ref int defaultInitRef; // Illegal: reference variables
>> // can't be default initialized
>
> But you can handle it like const members: you have to
> initialize these members in the ctor.
Furthermore I suggest that with "ref" marked Objects _can't_ be
null.
So ref Foo fr = null; is equally forbidden as
[code]
Foo f; // same as Foo f = null;
ref Foo fr = f;
[/code]
Why? First: null isn't an lvalue and even if "Foo f;" is one: if
it would be allowed, you have a useless reference, because it is
null and you can't assign a valid object to it (because you can
assign ref's just once)
Furthermore it solve the problem which I often annotate: not null
paramters.
void do_something(ref Foo fr) { <- "fr" can't be null, you can
trust it without any other validations.
I would love that. :)
More information about the Digitalmars-d
mailing list