Interested in D, spec confuses me.

Ali Çehreli via Digitalmars-d digitalmars-d at puremagic.com
Tue Feb 2 16:41:31 PST 2016


On 02/02/2016 04:31 PM, bubbasaur wrote:

 > Ok, but what would differ using immutable instead of const in your
 > example (AS ARGUMENTS)?
 >
 > See:
 >
 > import std.stdio;
 >
 >      struct Data { int x; }
 >      auto func1(Data* d) { return d.x; }
 >      auto func2(const(Data)* d) { return d.x; }

I cannot trust that a member of 'd' will not be modified later on. So, I 
cannot store 'd' as is. If I want to make use of its current state 
later, I must make a copy of it (which may have its own 
member-with-inderection issues).

In short, the promise of "I will not change members of 'd'" is not 
related to what can happen to that date by other parts of the code.

 >      auto func3(immutable(Data)* d) { return d.x; }

There, I know that 'd' will not change state. I can store it somewhere 
for later use; no need to copy. I can even pass it to a thread without 
needing a lock.

 >          auto value2 = d.x*func2(&d) + d.x;
 >          auto value3 = d.x*func3(cast(immutable)&d) + d.x;

That's not very nice because we've just fooled func3(). :) Although it 
required immutable data, we've given it mutable data. The programmer is 
on his or her own at that point. We hope the program will work correctly. :)

 > Functions 2 and 3 are acting in the same way

I like this explanation:

- A const parameter is a promise by the callee to not modify

- An immutable parameter is a requirement for the caller to never modify

Ali



More information about the Digitalmars-d mailing list