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

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 16 19:27:06 PDT 2015


On 10/16/2015 07:02 PM, Shriramana Sharma wrote:

 > your book which provides

I am glad that it is useful. :)

 > 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.

Actually, others gave the answer to that question, which was apparently 
not very clear. :)

In the context of your question, immutable is a requirement of the 
function from its user. It is a demand that the argument shall not 
mutate. That's why mutable cannot be considered as mutable.

For example, if you write a File struct and take the file name as 
string, you don't need to make a copy of the file name because you know 
that it will not mutate as long as your File object is alive. (You can 
cast immutable away with undefined consequences but it's a different 
issue. :) )

 > 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...

That and what I said above: the user can rely on this guarantee as well.

Ali



More information about the Digitalmars-d-learn mailing list