Learning delegates
Rémy Mouëza
remy.moueza at gmail.com
Sun Sep 8 15:16:30 UTC 2019
On Sunday, 8 September 2019 at 10:04:57 UTC, Joel wrote:
> I'm trying to understand delegates. Is there any good ways I
> can get a better understanding of them?
I am no compiler implementer, so what is below may contain a lot
of inaccuracies and conceptual shortcuts, but here is my view of
delegates in D. I hope this helps.
Delegates are fat function pointers.
D arrays are also fat function pointers: they can be implemented
as a struct with a size_t length and a pointer to the data:
sruct DArray(T) {
size_t length;
T * data;
}
D delegates can be implemented as a pointer to some context data
and a function pointer, something similar to D arrays:
struct DDelegate(Context, Return, Args) {
Context context;
Return function(Args) functionPointer;
}
The context can be:
- a struct value
- a class instance
- some data from a local function frame when the delegate is used
as a closure.
The compiler replaces a call to the delegate in the source code
by a call to the function pointer with the right data for runtime.
Something like:
dg.functionPointer(dg.context, "hello, world");
More information about the Digitalmars-d-learn
mailing list