spir <denis.s...@gmail.com> wrote:
First, what is the actual point of "new"?
Mostly, it's a remnant from C++.
I find this keyword rather helpful in that it reminds me the element is
referenced/heap-allocated/GC'ed. But is there any ambiguity on the
language's side? We cannot construct a class instance in any other way,
AFAIK, and "calling" a class can hardly have any other sense. Maybe
classes' opCall could be set to the creation routine (whatever new
calls); then we would get a single object-creation syntax.
Indeed it could. I believe Andrei Alexandrescu has discussed in favor of
such a change in the past.
Still, an other case when "new" annoys me is method chaining, because it
makes syntax heavier and less readable:
c = (new C(p)).do(x);
versus:
c = C(p).do(x);
Or, maybe, the parser could be clever enough to correctly decode:
c = new C(p).do(x);
One would think it possible to stop searching right upon first finding a
function call parentheses (as opposed to a template parentheses). This is
complicated by the allowance of the syntax 'new C;'.
Second, could there be a default constructor for classes, like for
structs? Namely, one that sets declared fields:
class C {int i;}
...
auto c = new C(1);
There could. :p
As for whether there should, I'm not sure. I would say such a
constructor should disappear, should the class designer add other
constructors. That, coupled with classes usually being more complex than
that (mine are, at least), this seems like a feature that would have
little actual air-time.
This is one great advantage of static languages, that the compiler knows
more thank to declarations. Isn't it sensible to use this knowledge when
helpful? I simply find the following stupid (I mean it's job for a
machine, not for a programmer):
class C {
int i;
this (int i) {this.i = i;}
}
As we already enjoy this feature for structs...
The syntax
this( int this.i ) {}
has been suggested for automatic initialization of fields. I like this
suggestion, but it is unlikely to find its way into the language any
time soon.
--
Simen