Immutability and other attributes, please review
Jacob Carlborg
doob at me.com
Thu Jun 14 06:21:33 PDT 2012
On 2012-06-14 14:47, Roman D. Boiko wrote:
> I was thinking that casting is bad here, but wanted to give the user
> ability to pass any object inside constructor. Now I see that this is a
> bad idea given transitivity of immutable.
If you want that and have it immutable you need to make a deep copy of
the passed in object to be safe. You could use const instead and also
making the argument const. If an argument is const you can pass both
mutable and immutable values, and const of course.
> In .NET readonly applies only to fields inside objects preventing
> assignments to them from other places than constructors. But I can
> assign another instance of an object with readonly fields to the same
> variable. Then I can pass that instance to some constructor and assign
> it to a readonly field.
You should be able to use const.
> How to achieve the same in D? As far as I understand, it is not possible
> for structs with immutable fields, and it is not clear for me about
> classes.
>
> In other words:
>
> Does a variable always point to the same place in memory and assigning
> to it simply copies data to that place? I don't understand whether it is
> possible to make it point to another place. That would be a mutable
> variable pointing to a type with immutable fields.
That's only possible with pointers in D.
> After that I want to
> assign an instance of that type to an immutable field in constructor.
> Can I do so, or that would be bad?
--
/Jacob Carlborg
More information about the Digitalmars-d-learn
mailing list