On Wednesday, 31 May 2023 at 03:29:33 UTC, Cecil Ward wrote:
I have to admit that I don’t really understand immutable. I have an idea that it could mean that an object has an address in ROM, so its value will never change. Maybe const doesn’t give you such a strong guarantee, disallows ‘you’ from modifying it but others might do so, but who knows.
There are two perspectives: that of the value handed to a function and that of the function taking the value. "immutable" (or "mutable") is a property of the value, "const" is a property of the function. If the function can work with mutable values, but in fact doesn't mutate them itself, it could also work with immutable values. The fact that others could modify your "const" value doesn't matter for immutable values, because they of course can't be modified by others. For the function it doesn't matter, because it only guarantees not to modify it itself, don't care about what other can or can't do.

Without a guarantee as strong as the first idea I can’t really
understand how const can work properly. "You treat it as const
so do not modify it, but it might not be eternally fixed and
unchanging" that doesn’t seem to have enough value to me.
Why? What guarantee are you missing?
Your function can work with mutable data, so you don't care if it can be modified also by others. Now it happens that you doesn't modify the data. So why shouldn't you be able to work on data that guarantees that it also will not be changed by others? You don't care for such modification anyway.

The meaning of "immutable" is: I cannot be modified. Not by you and not by anybody else. It's a property of a value. The meaning of "mutable" is: I can be modified by anybody. Work with me only if that is ok for you. It's a property of a value. The meaning of "const" is: I don't care if others modify the data or not, I won't modify it myself. It's a property of a function.

Reply via email to