How to initialize immutable variables with an expression that throws an exception to catch?

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Apr 7 20:44:20 UTC 2020


On Tue, Apr 07, 2020 at 07:52:36PM +0000, tsbockman via Digitalmars-d wrote:
[...]
> The problem in the language is that immutability is considered a
> permanent and fundamental property of a value, whereas it is actually
> a state that is entered after the initialization/construction of the
> value is complete, and exited when the value's memory is later
> reclaimed.
> 
> Construction of an immutable value should be done by making a mutable
> variable, mutating it to the desired state via any arbitrary sequence
> of normal operations, and then declaring the mutable stage of its life
> cycle complete via `cast(immutable)` or something. The only problem
> with this is making the compiler smart enough to prove that no mutable
> references to the data are used after that point, so that the
> operation can be @safe.
[...]

Actually, in the current language if you have a pure function that
constructs a (mutable) value of type T, and the compiler can infer that
the function returns a unique value, you can implicitly cast it to
immutable:

	struct T {
		int x;
		float[] y;
	}
	T makeT(int x, float[] y) pure {
		return T(x, y);	// N.B.: returns mutable
	}
	void main() {
		// N.B.: no need to cast:
		immutable(T) t = makeT(1, [ 2.3, 4.5 ]);
	}


T

-- 
Chance favours the prepared mind. -- Louis Pasteur


More information about the Digitalmars-d mailing list