difficulties with const structs and alias this / template functions

Dennis dkorpel at gmail.com
Mon Nov 19 12:28:43 UTC 2018


On Monday, 19 November 2018 at 02:39:32 UTC, Stanislav Blinov 
wrote:
> You're skimming the examples ;)

I'm not saying your examples don't work, I'm trying to understand 
the minimum requirements. You said:

"That's [constructors needing to be pure is] only for types with 
indirections (pointers), since `pure` guarantees that you do not 
mutate any global state."

My example was only to show that:
- a const constructor is insufficient for creating an immutable 
struct S
- an immutable or pure constructor is sufficient for creating an 
immutable struct S

You also showed that an inout constructor is sufficient too.

I don't understand why not any constructor would work. After all:

"value types are all copyable between mutable/const/immutable. So 
even if `return x + y` would yield a `const T`, you can still 
instantiate a T from it."

> Recall that member functions (including constructors) are just 
> functions in disguise:
> ...
> what that boils down to, conceptually, is:

I get what inout does know. But continuing on the constructor 
lowering, what strikes me is that:

S __ctor(ref const S this, int x) {
     this.x = x; // allowed, while `this` is a const(S)!
     // return this; automatically inserted
}

Knowing that a constructor may mutate the const(this) or 
immutable(this) members, why can't a mutable(this) constructor be 
called on an immutable(this), *unless* it is pure (which seems 
irrelevant to me)?


More information about the Digitalmars-d-learn mailing list