Why retain new ?

Mike Parker aldacron71 at yahoo.com
Sun Aug 5 18:18:08 PDT 2007


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();
}
========================



More information about the Digitalmars-d mailing list