Non-null objects, the Null Object pattern, and T.init

Adam D. Ruppe destructionator at gmail.com
Thu Jan 16 17:53:17 PST 2014


On Friday, 17 January 2014 at 01:42:38 UTC, Andrei Alexandrescu 
wrote:
>     static Widget init = new Widget(42);

The problem here is if it is in a mutable data segment:

Widget i; // implicitly set to init
assert(i is Widget.init); // uh oh
i.mutate();

Widget i2; // set to widget init...
assert(i is i2); // oh dear
// i2 now reflects the mutation done above!


And if the init is put in a read-only segment similar to a string 
buffer, we still get a segmentation fault when we try to mutate 
it.



I'm not necessarily against having the option, but I think it 
would generally be more trouble than it is worth. If you have an 
object that you want to guarantee is not null, make the nullable 
implementation

class Widget_impl {}

then define

alias Widget = NotNull!Widget_impl;

and force initialization that way.


More information about the Digitalmars-d mailing list