Copying a delegate

Jonathan M Davis jmdavisProg at gmx.com
Sat Sep 18 20:35:29 PDT 2010


Is it in any way possible to copy a delegate? Take this program for example:

import std.stdio;

void main()
{
    int a = 0;

    int func()
    {
        return a++;
    }

    int delegate() b = &func;
    int delegate() c = b;

    writeln(b());
    writeln(c());
    writeln(b());
}


It will print

0
1
2

But what if I wanted it to print

0
0
1


That doesn't work because you're just copying the pointer. Is there a way to 
actually do a deep copy of the delegate? I can see why this would be problematic 
if the delegate had reference types in its scope (since presumably, they'd have 
to be shallow copied unless you somehow had the equivalent of a copy constructor 
or postblit constructor for delegates), but even the ability to a do a shallow 
copy would be better than nothing. Is there any way to do that, or am I out of 
luck?

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list