Quick question about new semantics
Jonathan M Davis
jmdavisProg at gmx.com
Fri Sep 14 14:45:11 PDT 2012
On Friday, September 14, 2012 20:27:56 monarch_dodra wrote:
> 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?
Presumably, because it takes a different path in the compiler. S() could be
treated as a static opCall (certainly, that's how you define a pseudo-default
constructor on structs), whereas new S() newer would be. However, if anything,
I'm surprised that
auto s = S();
compiles given that other constructors are defined. But I guess that it just
always does S.init. There's also a decent chance that the code related to new
S() is the same for classes which _don't_ have an init value which would ever
be usable with new (and which definitely disallow new S() if there's no default
constructor).
I expect that it's a corner case that simply wasn't thought through, and
arguably it should work. I don't know that the spec says one way or the other
though (my guess is that it's silent on the matter, since it tends to be
fairly sparse). Certainly, without allowing that, constructing an S on the
heap which is S.init is a bit of a pain. It probably requires using either
emplace or taking the pointer to an element in an array (which would waste
memory).
I think that there's certainly an argument for allowing what you're trying to
do.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list