www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why immutable ?

reply Eyyub <eyyub34 hotmail.fr> writes:
I recently upgraded to the D 2, and i would like understand for which reason
they are the immutable keyword !

Thx
Dec 12 2010
parent reply "Simen kjaeraas" <simen.kjaras gmail.com> writes:
Eyyub <eyyub34 hotmail.fr> wrote:

 I recently upgraded to the D 2, and i would like understand for which  
 reason they are the immutable keyword !
immutable means 'this data cannot change'. It is different from const in that the latter means 'I cannot change this data (but someone else may change it from under my feet)'. It is added for simplification of sharing (no locking required), and to a certain extent to allow for better optimization and functional programming. -- Simen
Dec 12 2010
parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On Sunday 12 December 2010 08:03:57 Simen kjaeraas wrote:
 Eyyub <eyyub34 hotmail.fr> wrote:
 I recently upgraded to the D 2, and i would like understand for which
 reason they are the immutable keyword !
immutable means 'this data cannot change'. It is different from const in that the latter means 'I cannot change this data (but someone else may change it from under my feet)'. It is added for simplification of sharing (no locking required), and to a certain extent to allow for better optimization and functional programming.
You should probably check out this: means that any data reachable this page: http://www.digitalmars.com/d/2.0/const3.html And of course, Andrei's book, The D Programming Language would be a great resource, but the primary benefit of immutable releates to threading. const doesn't buy you anything with regards to threads. Just because one reference or pointer is a reference or pointer to const does not mean that _all_ references or pointers to that data point to const. Mutexes and the like can't assume _anything_ based on const. immutable, on the other hand, will _never_ change. You can rely on that. So, if you have a reference or pointer to immutable data, you _know_ that it won't change. This makes sharing between threads easy without being error-prone. For instance, std.concurrency uses immutable objects for message passing between threads. That wouldn't work with const, because the original thread might still be able to alter the data. Also, immutable data can (at least theoretically) be put in read-only memory, which certainly can't be done with const. So, there are definite gains from immutable. Most deal with threading, but there are others. const is still very useful (particularly since it allows you to have a function that can take either a mutable or immutable argument) but it plays a very different role overall. - Jonathan M Davis
Dec 12 2010