Why can't function expecting immutable arg take mutable input?
Mike Parker via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Oct 16 04:27:57 PDT 2015
On Friday, 16 October 2015 at 10:35:23 UTC, Shriramana Sharma
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?
>
>
The contract of immutable is such that any reference to immutable
data is a guarantee that no reference to the same data will
modify it anywhere in the program. Passing mutable data to a
function where an immutable parameter is declared would break
that contract, since the data could be modified through the
original reference. The compiler can take advantage of such a
strict contract to make optimizations it would otherwise be
unable to.
const only guarantees const data will not be modifed through a
single reference, but says nothing about other references to the
same data. A const parameter can accept const, immutable, and
mutable arguments.
More information about the Digitalmars-d-learn
mailing list