T.init and @disable this

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Fri Oct 5 23:54:23 PDT 2012


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


More information about the Digitalmars-d mailing list