Delegate is left with a destroyed stack object
Peter Alexander
peter.alexander.au at gmail.com
Wed Oct 30 13:35:13 PDT 2013
On Wednesday, 30 October 2013 at 09:20:40 UTC, Lionello Lunesu
wrote:
> On 10/29/13, 22:42, David Nadlinger wrote:
>> On Tuesday, 29 October 2013 at 21:41:25 UTC, Lionello Lunesu
>> wrote:
>>> So a copy should have been made of the live object, not the
>>> destructed
>>> one. Correct?
>>
>> No. There should only be one struct instance, the one living
>> (forever)
>> in the closure context.
>>
>> David
>
> Why? It's a struct. It should be completely fine to create a
> copy [on the heap] for the closure context.
That would be worse:
void increment(ref int x) { ++x; }
void run(void delegate() f) { f(); }
void main()
{
int x = 0;
run( { increment(x); } );
writeln(x);
}
If the closure took a copy of x then this would write 0.
Certainly not what I would expect.
I think not running the destructor is the best option (although
to be honest, I'm not a huge fan of closures to begin with, for
exactly these sorts of reasons -- they only really work well in a
pure functional setting).
More information about the Digitalmars-d
mailing list