toriningen
toriningen

Reputation: 7480

d2: immutability of partially known structures

In D, immutable is transitive, so assignments to any field of immutable structure is prohibited. As far as I understand, immutable structure variable is strongly guaranteed to be never ever changed, and all it's contents too.

But what if I have declared thing like this?

struct OpaqueData;
immutable(OpaqueData*) data;

How can D guarantee transitive immutability of structure not implemented in D and possibly having indirections?

What is right way to encapsulate such kind of pointer to opaque data in immutable class?

Upvotes: 2

Views: 101

Answers (1)

user438034
user438034

Reputation:

Since you don't know of any fields in OpaqueData, you can't assign to any contents of it in the first place.

You can, of course, break the type system entirely by casting away immutable (D does give you the power to do so) and assigning to the raw memory an OpaqueData* value points to, but then you're asking for whatever problems you'll end up with... If you don't do this and respect that your OpaqueData pointer is immutable, you cannot alter it in any way due to the transitive nature of type qualifiers.

This is, in fact, the entire point of them: They are mathematically sound.

Upvotes: 5

Related Questions