Static opCall and class instantiation

Kirk McDonald kirklin.mcdonald at gmail.com
Sat May 20 15:28:17 PDT 2006


I've been reading an old thread from 2004 called "Clumsy class 
instantiation quibble." This example here gives one solution to the 
"problem" (which is hardly a serious concern, really it's just syntactic 
sugar, but bear with me):

http://www.dsource.org/projects/tutorials/wiki/OpCallExample

I like this. It wraps the "new" keyword in a static opCall, allowing you 
to drop the new keyword whenever you construct a class instance.

(The example claims this is the "C++ syntax," but the semantics are 
quite different, as when you do this in C++ you are allocating it on the 
stack.)

Python does exactly this. Like D (and Java, for that matter), class 
instances can only be created by reference, meaning the new keyword is 
redundant, and so the language dropped it entirely. I never understood 
why Java bothered to keep it, and I still don't get it in D. It's still 
useful for structs, which can be put on the stack, yes? So I think D 
should support both syntaxes.

To sum up suggestions (posted by "Harvey" <hstroud at ntlworld.com>) from 
the old thread:

SomeClass  sc1;      // null reference
SomeClass  sc2();    // reference assigned to GC-allocated instance
SomeClass  sc3 = SomeClass(); //  same as above
sc1 = SomeClass();   // sc1 assigned to GC-allocated instance
sc1 = new SomeClass(); // same as above

Because there is only one way to instantiate a class, all of these 
different syntaxes mean the same thing. The "new" keyword is not needed, 
but should still be kept. And if the various Python code I've read is 
any guide, dropping the "new" keyword is still eminently clear for the 
reader.

As far as I could tell, the original thread never really came to a 
conclusion. I was wondering what the D community thought of it now, 
almost exactly two years later. Thoughts?

A post from the original thread:
http://www.digitalmars.com/drn-bin/wwwnews?digitalmars.D/1511

-Kirk McDonald



More information about the Digitalmars-d mailing list