Are value types immutable by definition?

后端 未结 12 1510
陌清茗
陌清茗 2020-12-04 09:18

I frequently read that structs should be immutable - aren\'t they by definition?

Do you consider int to be immutable?

int i         


        
12条回答
  •  Happy的楠姐
    2020-12-04 09:33

    No, they are not. Example:

    Point p = new Point (3,4);
    Point p2 = p;
    p.moveTo (5,7);
    

    In this example moveTo() is an in-place operation. It changes the structure which hides behind the reference p. You can see that by look at p2: It's position will also have changed. With immutable structures, moveTo() would have to return a new structure:

    p = p.moveTo (5,7);
    

    Now, Point is immutable and when you create a reference to it anywhere in your code, you won't get any surprises. Let's look at i:

    int i = 5;
    int j = i;
    i = 1;
    

    This is different. i is not immutable, 5 is. And the second assignment doesn't copy a reference to the structure which contains i but it copies the content of i. So behind the scenes, something completely different happens: You get a complete copy of the variable instead of only a copy of the address in memory (the reference).

    An equivalent with objects would be the copy constructor:

    Point p = new Point (3,4);
    Point p2 = new Point (p);
    

    Here, the internal structure of p is copied into a new object/structure and p2 will contain the reference to it. But this is a pretty expensive operation (unlike the integer assignment above) which is why most programming languages make the distinction.

    As computers become more powerful and get more memory, this distinction is going to go away because it causes an enormous amount of bugs and problems. In the next generation, there will only be immutable objects, any operation will be protected by a transaction and even an int will be a full blown object. Just like garbage collection, it will be a big step forward in program stability, cause a lot of grief in the first few years but it will allow to write dependable software. Today, computers just aren't fast enough for this.

提交回复
热议问题