Problem with taking inout, const references

Ali Çehreli acehreli at yahoo.com
Wed Mar 26 10:34:09 PDT 2014


On 03/26/2014 01:21 AM, Uranuz wrote:

 > If inout is treated as const does it mean that in this operator I can't
 > assign new value to cookie object.

I have not investigated the compiler code but the following is very 
logical to me.

inout is not a template mechanism. The code gets compiled once. What 
happens is, the inout from some variable is transferred to some other 
variable(s).

Since inout must work with mutable, const, and immutable, and since 
const binds to all three, it is easy for the compiler to assume inout is 
const inside the code and reject code that tries to modify an inout 
variable (even if inout is 'mutable' for some calls to the function).

After compiling the code, the compiler also ensures that the inout that 
is returned from the function is compatible with the calling code. For 
example, if the source inout array were immutable, a slice of it should 
not be assigned to a mutable slice at the caller site:

inout(int)[] foo(inout(int)[] arr)
{
     return arr;
}

     immutable(int)[] imm = // ...;

     int[] result = foo(imm);    // ERROR

 > In this case it means that I still
 > should make separate class method with the same body to woraround this.
 > I think that it's a bug. Am I right?

It is not a bug. If the member function makes modifications to the 
object, it cannot be inout, because it can work only with mutable objects.

Ali



More information about the Digitalmars-d-learn mailing list