@disable("reason")

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Jan 8 07:03:26 UTC 2020


On Tuesday, January 7, 2020 5:23:48 PM MST Marcel via Digitalmars-d-learn 
wrote:
> Hello!
> I'm writing a library where under certain conditions i need all
> the default constructors to be disabled. I would like to tell the
> user why they can't instantiate the struct.
> Is there a way to do that?

In terms of an error message? Not really. You can put a pragma(msg, ""); in
there, but that would always print, not just when someone tried to use it.
I'd suggest that you just put the information in the documentation. If they
write code that doesn't work because of you using

    @disable this();

the documentation is where people will look to find out why anyway.

And BTW, structs don't have default constructors in D. So, maybe it's just a
question of terminology rather than you misunderstanding the semantics, but
all variables in D get default initialized with their type's init value,
including structs, and you can't actually declare a default constructor for
a struct. So, if you have

    @disable this();

in a struct, all that that's doing is disabling default initialization, not
default construction. So, code like

    MyStruct ms;

or

    MyStruct[] arr;

won't compile, because they require default initialization. But even then,
you don't actually get rid of the default value of the struct. You just make
it so that it doesn't get used implicitly. Code such as

    auto ms = MyStruct.init;

or

    MyStruct ms = MyStruct.init;

will still work. So, you still potentially have to worry about the type's
init value being used (though you could just document that no one should
ever use its init value explicitly, and that they will have bugs if they do,
not that that actually prevents people from using it incorrectly; it just
informs them that they shouldn't). It's unlikely that many people will try
to use the init value explicitly, but some generic code may do so (e.g.
IIRC, std.algorithm's move function uses it on the source variable after
moving the value to the target variable).

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list