Here's something from TDPL, page 292:

string process(string input) { return input; };

string s1 = "blah";
string s2 = process(s1);
assert(s1 == "blah");   // never fails

I've added the return in process(), it wasn't there. Andrei states that it's 
impossible for s2 to be changed after the assignment. And that the code above 
never fails.

I agree that in this case s1 and s2 will remain the same. But this has to do 
*not just* with immutability, but with the fact that s1 is passed by value. I 
think that should be mentioned here.

Look what happens if I make the string a reference parameter, and do some 
innocent appending:

string process(ref string input) 
{
    input ~= "lala";
    return input; 
};

void main()
{
    string s1 = "blah";
    string s2 = process(s1);
    assert(s1 == "blah");   // fails
}

It's just nitpicking, I know. And I'm sure Andrei was specifically documenting 
only that first example. But I do think it was worth mentioning that 
immutability on individual elements isn't a safe bet unless you're sure the 
function does not take a reference parameter.

Reply via email to