Proposal : allocations made easier with non nullable types.

grauzone none at example.net
Mon Feb 9 06:22:11 PST 2009


Alex Burton wrote:
> I think it makes no sense to have nullable pointers in a high level language like D.
> 
> In D :
> 
> X x = new X;
> This is a bit redundant, if we take away the ability to write X x; to mean X x = 0; then we can have X x; mean X x = new X;
> If the class has a ctor then we can write X x(32); instead of X x = new X(32);
> Only when the types of the pointer and class are different do we need to write X x = new Y;

Add this code to your class X:

static X opCall(T...)(T x) {
	return new X(x);
}

Then you can write:
 > auto x = X();

Can it get any less redundant? The opCall is a bit annoying, but needs 
to be written only once.

> We can do this syntactically in D because classes cannot be instantiated on the stack (unless scope is used, which I have found a bit pointless, as members are not scope so no deterministic dtor)
> 
> This makes the code much less verbose and allows code to change from X being a struct to X being a class without having to go around and change all the X x; to X = new X;

For structs, use opCall() to initialize them. opCall is the best way to 
initialize a struct, because struct literal are totally utterly useless.

If you use opCall to initialize classes as well (see above), then the 
syntax for initializing structs and classes will be exactly the same.

> As I said in the nullable types thread:
> Passing 0 or 0x012345A or anything else that is not a pointer to an instance of X to a variable declared as X x is the same as mixing in a bicycle when a recipe asks for a cup of olive oil.
> 
> There are much better, and less error prone ways to write code in a high level language than allowing null pointers.

Like what?

> Alex



More information about the Digitalmars-d mailing list