Suggestion: shortcut for 'new X'

Kristian kjkilpi at gmail.com
Thu Aug 24 09:43:44 PDT 2006


On Thu, 24 Aug 2006 19:08:22 +0300, BCS <BCS at pathlink.com> wrote:

> Kristian wrote:
>> On Thu, 24 Aug 2006 18:10:12 +0300, Oskar Linde   
>> <oskar.lindeREM at OVEgmail.com> wrote:
>>
>>> Kristian wrote:
>>>
>>>> How about this:
>>>>      Obj obj1 = new Obj;
>>>>     Obj obj2 = new Obj(10);
>>>>  could be reduced to:
>>>>      Obj obj1 = new;
>>>>     Obj obj2 = new(10);
>>>>  This way only one class name would be required per variable. (That  
>>>> is,  one at maximum: "Obj obj1 = new, obj2 = new(10);" is also valid  
>>>> of  course.) Redundance would be reduced.
>>>
>>>
>>> You can already do:
>>>
>>> auto obj1 = new Obj;
>>> auto obj2 = new Obj(10);
>>>
>>> which takes care of the redundant Obj.
>>   Yes, and it's nice.
>> But you cannot always use auto.
>>  Obj func() {
>>     Obj ret = new;
>>      ret.doSomething();
>>     ...
>>     return(ret);
>> }
>>  That would be nice too. :)
>
> IIRC this works:
>
> Obj func() {
>      auto ret = new Obj;
>
>      ret.doSomething();
>      ...
>      return(ret);
> }

It seems that you're right. Thanks for pointing it out. :)

However, I don't think that it's not good programming style to use auto a  
lot. :/

Consider the following:

Obj func2() {...}

void func() {
     auto obj = func2();
}

When looking at 'func()' only it's impossible to know the type of 'obj'.

Of course I could write "auto Obj obj" or "Obj obj", but it's inconsistent  
with 'anonymous autos':

void func() {
     auto Obj obj1 = func();
     auto obj2 = new Obj;
}

I would really prefer the following:

void func() {
     Obj obj1 = func();
     Obj obj2 = new;
     Obj obj3;
}

Or:

void func() {
     auto Obj obj1 = func();
     auto Obj obj2 = new;
     auto Obj obj3;
}

(Note the usage of the shortcut of 'new'.)



More information about the Digitalmars-d mailing list