Pure functions as initializers for immutable structures?

Michel Fortin michel.fortin at michelf.com
Mon Oct 18 13:52:25 PDT 2010


On 2010-10-18 14:31:26 -0400, Tomek Sowiński <just at ask.me> said:

> Call me crazy, but I think it is safe to implicitly convert a pure  
> function's return value to immutable. What you think?

Well, it depends on the arguments of the pure function. Here's two 
cases where it won't work.

1. With the new pure semantics, a pure function is allowed to mutate 
arguments passed to it, so a reference to the function's return value 
could escape through it. For instance:

	class C {}

	pure C func(C* c) {
		*c = new C;
		return *c;
	}

	C c1;
	immutable(C) c2 = func(*c1);
	// now you have mutable c1 and immutable c2 pointing to the same 
(mutable?) object.

A pure function where all the arguments are const or immutable does not 
have this problem. But it could have the second one though...

2. If you pass mutable or const arguments (arguments that are not 
immutable) to the pure function, the function could put a reference to 
those arguments inside the struct, and casting it to immutable would 
cause someone to have an immutable reference while someone else has a 
mutable one to the same piece of memory:

	struct S { const(char)[] a; }

	pure S func(const(char)[] a) {
		S s;
		s.a = a;
		return s;
	}

	char[] someString = "hello".dup;
	immutable(S) s = func(someString);
	// now you have mutable someString and immutable s.a pointing to the 
same (mutable?) string.

Basically, if all the arguments are immutable then it'd be guarantied 
that it's safe to cast the result as immutable. But a const argument 
can break this guaranty.

So I'd precise your assertion by saying it is safe to implicitly 
convert a pure function's return value to immutable, but only when all 
the arguments you feed to it are immutable.

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/



More information about the Digitalmars-d mailing list