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

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 16 08:04:55 PDT 2015


On Fri, Oct 16, 2015 at 04:05:19PM +0530, Shriramana Sharma via Digitalmars-d-learn wrote:
> Hello. I still haven't wrapped my mind around the const/immutable
> thing yet and am still stuck in C/C++ mode. :-(
> 
> A function that takes mutable arguments cannot be called with
> immutable input at the call site since it does not promise to *not*
> mutate the input.  That's of course clear.
> 
> Why can't a function that takes an immutable argument be called with a
> mutable input at the call site?

What you want here is const, not immutable.

Const is a guarantee that the argument will not be modified *by the
function*. Immutable, however, is a much stronger guarantee: that the
argument will not be modified by *anyone*. That is, the compiler is free
to assume that the result of calling a pure function that takes
immutable arguments will never ever change, no matter what, so it's safe
to elide all but the first call to that function and cache its result.
You can't do this with const, because it's possible that somebody may
hold a mutable reference to the data and mutate it between calls.


[...]
> I understand that const can refer to either mutable or immutable, so
> does this mean I should replace all occurrences of `string` in
> arguments and return values of functions by `const(char)[]`?
[...]

If your functions don't need the stronger guarantee of immutable, yes,
use const(char)[] instead. It's what const was designed for -- to take
arguments that can be either mutable or immutable.


T

-- 
Tech-savvy: euphemism for nerdy.


More information about the Digitalmars-d-learn mailing list