Why can't function expecting immutable arg take mutable input?

Jakob Ovrum via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 16 19:43:53 PDT 2015


On Saturday, 17 October 2015 at 02:03:01 UTC, Shriramana Sharma 
wrote:
> Ali Çehreli wrote:
>
> http://ddili.org/ders/d.en/const_and_immutable.html#ix_const_and_immutable.parameter, %20const%20vs.%20immutable
>
> Hi Ali – I take this chance to personally thank you sincerely 
> for your book which provides much-needed hand-holding in my 
> baby D-steps. I did read that chapter already and IMO you have 
> given clear instructions as to when to use const and when 
> immutable.
>
> My question was however to the root of the issue, as to *why* 
> the compiler cannot consider mutable as immutable just like in 
> C/C++ any non-const can be taken as const.
>
> It would seem that the answer is one related to optimization. 
> Obviously, labeling an argument as immutable can be done only 
> if we are sure that we will have to process only immutable 
> input, thereby paving the opportunity for the compiler to 
> optimize some memory access or allocation or such – I'm not 
> much clear beyond that but that's enough for me now...

It appears that the linked chapter doesn't explain *why* you 
would want to receive immutable arguments.

In my experience, the most common motivation is a desire to 
escape a reference to the argument. We want to read the data 
later, but when we do, we want it to be unchanged from when we 
received it:

---
struct S
{
     immutable(int)[] numbers;

     this(immutable(int)[] numbers)
     {
         this.numbers = numbers;
     }

     void printNumbers()
     {
         import std.stdio;
         writeln(numbers);
     }
}

immutable numbers = [1, 2, 3];
auto s = S(numbers);
/* ... */
s.printNumers(); // [1, 2, 3]
---

In the above code, *no matter what code is run between 
construction and `printNumbers`*, it will always print the same 
numbers it received at construction, as the numbers are 
immutable. Because of this guarantee, S.numbers can simply alias 
the constructor argument as seen in the constructor body, instead 
of say, copying the numbers into a new heap-allocated copy of the 
array. If we used const instead of immutable, there would be no 
such guarantee, as const can refer to mutable data: the numbers 
could have been overwritten between construction and the call to 
`printNumbers`.

Another common use of immutable is to share data between multiple 
threads. As immutable data never changes after initialization, it 
can be passed between threads and read freely without worrying 
about data races.

const in D simply exists to bridge mutable and immutable data. It 
is different from C++'s const, despite sharing the same name.



More information about the Digitalmars-d-learn mailing list