Quick question about new semantics

Maxim Fomin maxim at maxim-fomin.ru
Sat Sep 15 03:00:35 PDT 2012


2012/9/14 monarch_dodra <monarchdodra at gmail.com>:
> I have a struct, which defines a constructor that takes an argument.
>
> Now, I'd like to new this object, to it's default T.init value (eg call new,
> but now constructors):
>
> --------
> struct S
> {
>     this(int);
> }
>
> void main()
> {
>     auto p1 = new S;
>     auto p2 = new S();
> }
> --------
> main.d(8): Error: constructor main.S.this (int) is not callable using
> argument types ()
> main.d(8): Error: expected 1 function arguments, not 0
> main.d(9): Error: constructor main.S.this (int) is not callable using
> argument types ()
> main.d(9): Error: expected 1 function arguments, not 0
> --------
> Is this a bug? If "auto a = S();" is legal, how can "auto p = new S();" not
> be?


S() and new S() produces expressions of different types: S and S*
respectively. Also the first one is very close to (may be even equal)
S.init. Arguments to new expressions are currently must be consistent
with constructor arguments. To be more precise, dmd converts new
expressions to allocator call and then tries to place constructor
call, if any. Thus, if any constructor exists (and in case of structs
they cannot have no arguments), arguments passed to new must be
consistent with arguments of one of the constructors. Because in your
case arguments of new expression doesn't match to any constructor
call, dmd issues error.

So, I think this a enhancement request rather than a compiler bug.


More information about the Digitalmars-d-learn mailing list