Why retain new ?

Chris Nicholson-Sauls ibisbasenji at gmail.com
Sun Aug 5 23:29:38 PDT 2007


Mike Parker wrote:
> Kirk McDonald wrote:
>> Alex Burton wrote:
>>> Given that all classes are on the heap, why not replace the syntax :
>>> CmdLin cl = new CmdLin(argc, argv);
>>> with
>>> CmdLin cl(argc,argv);
>>> saving some typing and repetition.
>>>
>>> Only when casting to base class would you want to do :
>>> CmdLinBase cl = CmdLin(argc,argv);
>>
>> You can already say this:
>>
>> auto cl = new CmdLin(argc, argv);
>>
>> The syntax you suggest looks too much like the C++ syntax for 
>> allocating on the stack. Using 'new' is more explicit, and makes it 
>> abundantly clear where the class is being allocated, and what its 
>> lifetime is.
>>
> 
> Another thing is that these are two different function calls in D. With 
> the new keyword, you are calling the constructor. Without it, you are 
> calling opCall. So you can simulate this feature by making use of static 
> opCall like so:
> 
> ========================
> class A
> {
>     static A opCall()
>     {
>         return new A;
>     }
> }
> 
> void main()
> {
>     A a = A();
> }
> ========================

And along the lines of the C++ comparison, it might be confusing to some 
that 'Class var(123);' creates an object while 'Class var;' does not.  I 
like that 'new' sticking out, anyhow.  Its good visual aid.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list