Is this really intended??

Steven Schveighoffer schveiguy at gmail.com
Sun Oct 11 18:57:55 UTC 2020


On 10/10/20 8:16 PM, claptrap wrote:
> struct Foo
> {
>      int i;
>      void opAssign(int rhs) { this.i = rhs; }
>      void reset() { i = 0; }
> }
> 
> class Bar
> {
>      Foo foo;
> 
>      this()
>      {
>          foo.i = 0;    // *1
>          foo.reset();  // *2
>          foo = 42;
>      }
> }
> 
> With *1 & *2 commented out...
> 
> onlineapp.d(19): Error: cannot implicitly convert expression x of type 
> int to Foo
> onlineapp.d(19):        this.foo = x is the first assignment of this.foo 
> therefore it represents its initialization
> onlineapp.d(19):        opAssign methods are not used for 
> initialization, but for subsequent assignments

Hm.. yeah, this seems not right. The compiler should just go ahead and 
initialize it if you try to call any methods on it (including opAssign) 
before initialization.

note that if you define a constructor for Foo that takes an int, it 
would work (and use that when you assigned it to 42).

But it shouldn't need this, IMO.

What's really bizarre is if you comment *1 out, it still complains. If 
you called reset on it, is it not already initialized???!

> 
> With *2 commented out it compiles with no errors
> 
> With *1 commented out...
> 
> onlineapp.d(19): Error: cannot implicitly convert expression x of type 
> int to Foo
> onlineapp.d(19):        this.foo = x is the first assignment of this.foo 
> therefore it represents its initialization
> onlineapp.d(19):        opAssign methods are not used for 
> initialization, but for subsequent assignments
> 
> Arn't structs supposed to be default initialised?
> 
> But in a constructor a struct member is not? If you write to a field in 
> a struct member suddenly it is considered initialised?
> 
> And yet it's OK to call a method on the struct that is not initialised, 
> but if you do it's still uninitialised?
> 
> Why should
> 
> foo.i = 0;
> foo.reset();
> 
> Result in the compiler changing whether it's OK to call opAssign?
> 
> That's some weird ****.

This makes no sense. I think this is worth a bug report. The compiler 
should be a bit smarter (dumber?) on flow checking here.

-Steve


More information about the Digitalmars-d mailing list