Class member function calls inside ctor and dtor

Timon Gehr timon.gehr at gmx.ch
Sun Jan 28 17:12:30 UTC 2018


On 28.01.2018 02:13, Jonathan M Davis wrote:
> Yes, but you can have that problem even without getting inheritance involve.
> For instance,
> 
> class C
> {
>      immutable string s;
> 
>      this()
>      {
>          s = foo();
>      }
> 
>      string foo()
>      {
>          return s ~ "foo";
>      }
> }
> 
> When foo is called from the constructor, s is null, whereas every time it's
> accessed after that, it's "foo", meaning that the first time, foo returns
> "foo" and all other times, it returns "foofoo". You can also do
> 
> class C
> {
>      immutable string s;
> 
>      this()
>      {
>          s = s ~ "foo";
>      }
> }
> 
> which surprised me. I thought that the compiler prevented you from using an
> immutable variable before it was assigned in the constructor, but it
> doesn't. It actually can't if you call any member functions unless it
> required that all const and immutable members be initialized before calling
> other functions, but it could at least prevent it within the constructor. It
> doesn't though.

At some point it will need to, as the current behavior can be used to 
violate type system guarantees.


More information about the Digitalmars-d mailing list