T.init and @disable this

deadalnix deadalnix at gmail.com
Thu Oct 11 10:42:27 PDT 2012


Le 06/10/2012 08:54, Andrei Alexandrescu a écrit :
> On 10/4/12 7:33 AM, kenji hara wrote:
>> But, I also agree that T.init _sometimes_ *unsafe*.
>> 1) If T has @disable this(), T.init will returns an object which just
>> initialized (== the value itself is never undefined), but not
>> constructed (might be logically invalid object).
>> 2) If T is nested struct, it's frame pointer is always null. It might
>> cause access violation by its member function call.
>>
>> I came up with just now: The use of such unsafe T.init should be
>> allowed only inside @system/@trusted functions.
>> I think it is acceptable limitation.
>>
>> Thoughts?
>
> I think we should go back to the rationale for introducing @disable. The
> most important motivating examples were:
>
> 1. Defining NonNull references
>
> 2. Defining objects that are movable but not copyable
>
> For NonNull references, the existence of an usable T.init would be a
> definite problem because it would suddenly allow the existence of, well,
> a null reference.
>
> For (2) there may also be breakage, although more subtle: uncopyable
> objects are often associated with carefully-guarded resources (e.g.
> mutex locks) and shouldn't exist without special creation.
>
> However, T.init is good to have as an always available value inside
> static code that tests e.g. for capabilities.
>
> (There's been a long-standing similar problem in C++ as well.)
>
> A possible solution is to allow T.init for uncopyable types as an
> unresolved reference: code can use it symbolically, but if it tries to
> actually do things with it at runtime that would be a link-time error.
>
> Another solution would be to define T.init for uncopyable types as
> function that just throws if ever called.
>
> Thoughts?
>
>
> Andrei

.init is needed .

It is what the struct is initialized to before any constructor is 
called. It may be an invalid state (it is for chars, it is for float, it 
is for many classes, so why can't it be for structs ?).

That property can be made unsafe to use.

And the compiler must ensure that the struct is initialized. IE:

struct S { @disable this(); }

S s; // OK
foo(s); // Error, s is not initialized.
s = S.init; // Error in @safe code.
foo(s); // OK is @system code.
s = S(); // Error no default constructor (or may be we should allow 
argument-less constructor).


More information about the Digitalmars-d mailing list