A new instance of a variable?

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Nov 13 10:18:45 PST 2015


On 13.11.2015 18:44, Ish wrote:
> immutable int* j = new immutable int(i);
> gives error:
> locks1.d:27: error: no constructor for immutable(int);

Looks like your D version is rather old. I had to go back to dmd 2.065 
to see that error. 2.065 is from February 2014. We're at 2.069 now. I'd 
recommend updating the compiler.

If that's not an option, here are two variants that work with 2.065.

Allocate mutable, assign value, cast to immutable:
----
int* jm = new int;
*jm = i;
immutable int* j = cast(immutable) jm;
jm = null; /* So that you don't accidentally alter the data through jm. */
----
Pretty straight-forward, but verbose and not fool-proof at all.


Array literal:
----
immutable int imm = i; /* or declare i immutable to begin with */
immutable int* j = [imm].ptr;
----
Looks nicer, but allocates more space than necessary.



More information about the Digitalmars-d-learn mailing list