A new instance of a variable?

Marc Schütz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Nov 13 10:10:36 PST 2015


On Friday, 13 November 2015 at 17:44:31 UTC, Ish wrote:
> On Friday, 13 November 2015 at 16:06:51 UTC, Alex Parrill wrote:
>> On Friday, 13 November 2015 at 15:49:01 UTC, Ish wrote:
>>>
>>> foreach (i; 0..5) {
>>>   immutable int j = i;
>>>   etc.
>>> }
>>> I want each j to be assigned separate memory so that it can 
>>> be passed to a calle function and not overwritten by next 
>>> value of i in foreach()??
>>
>> Just like in C, you'll have to allocate storage for each 
>> object you create.
>>
>>     immutable int* j = new immutable int(i);
>>
>> Though if you use `new`, you can let the GC free them.
>>
>> But if the data is immutable, then there's no point in 
>> allocating separate objects for each number, since they can't 
>> be changed.
>
> immutable int* j = new immutable int(i);
> gives error:
> locks1.d:27: error: no constructor for immutable(int);
>
> I need to allocate separate objects as the value is passed to a 
> separate thread as:
> void incrementer(immutable int* nterm, shared(Lock) lock) { 
> etc. }

This compiles for me with 2.068, 2.069 and latest Git (Linux 
x86_64):

void main() {
     foreach(i; 0 .. 10000) {
         immutable int* j = new immutable int(i);
     }
}

Can you post more of your actual code?


More information about the Digitalmars-d-learn mailing list