Overzealous immutable and classes

Gareth Charnock gareth.charnock at gmail.com
Thu Jul 15 17:40:26 PDT 2010


So having got a collectors' edition TDPL, I though I'd have a try at 
writing some concurrent code. The idea was a worker thread(s) would do 
some work and write the results to some immutable objects. These would 
get passed to an indexer thread that would do neat stuff like indexing 
the references to the objects in things like hash tables and such, 
performing any reduce type operations along the way. These views would 
then be passed back to workers in due course. Unfortunately I hit a 
snag. It appears you can't do this:

class A {
    ...
}
immutable A a1 = new immutable(A);  //pointer to a real, immutable object
immutable A a2;  //pointer to null
a2 = a1;   //error, guess I doomed a2 to a life of being useless

I thought that as such assignments don't change the underlying objects 
in memory, they would be fine. Compare to:

immutable(char)[] s1 = "hello world"; //fat pointer to a section of 
immutable memory
immutable(char)[] s2;  //fat pointer to null
s2 = s1; //fine

The only solutions I can think of:
1) Use a pointer to a class. Works, but that just seems very unsafe and 
just plain un-D-ish. We also have to dereference two pointers.
2) Work entirely with immutable(A)[], which is not quite as crazy as it 
seems as we are copying about arrays of pointers rather than arrays of 
A. It's still quite crazy.
3) Write some sort of wrapper struct to hide the pointer.
4) Perhaps ref works like C++ int&?
ref immutable(A) ref_a //error
Nope.

So is this intended behavior? Am I missing something obvious?



More information about the Digitalmars-d-learn mailing list