Skip to content

Commit f247223

Browse files
authored
Merge pull request dlang#3599 from ntrel/method-delegates
[spec/function] Tweak delegate docs Signed-off-by: Dennis <dkorpel@users.noreply.github.com> Signed-off-by: Nicholas Wilson <thewilsonator@users.noreply.github.com> Merged-on-behalf-of: Nicholas Wilson <thewilsonator@users.noreply.github.com>
2 parents 263147a + 531115e commit f247223

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

spec/function.dd

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3143,7 +3143,9 @@ void main()
31433143

31443144
$(P The stack variables referenced by a nested function are
31453145
still valid even after the function exits (NOTE this is different
3146-
from D 1.0.) This is called a $(I closure).
3146+
from D 1.0).
3147+
This combining of the environment and the function is called
3148+
a $(I dynamic closure).
31473149
)
31483150

31493151
$(P Those referenced stack variables that make up the closure
@@ -3184,6 +3186,8 @@ void main()
31843186
a closure and is an error.
31853187
)
31863188

3189+
$(H4 $(LNAME2 method-delegates, Method Delegates))
3190+
31873191
$(P Delegates to non-static nested functions contain two pieces of
31883192
data: the pointer to the stack frame of the lexically enclosing
31893193
function (called the $(I context pointer)) and the address of the
@@ -3193,39 +3197,40 @@ void main()
31933197
Both forms of delegates are indistinguishable, and are
31943198
the same type.
31953199
)
3200+
$(P A delegate can be set to a particular object and method using `&obj.method`:)
31963201

31973202
$(SPEC_RUNNABLE_EXAMPLE_RUN
31983203
------
31993204
struct Foo
32003205
{
3201-
int a = 7;
3202-
int bar() { return a; }
3206+
int a;
3207+
int get() { return a; }
32033208
}
32043209

3205-
int foo(int delegate() dg)
3210+
int add1(int delegate() dg)
32063211
{
32073212
return dg() + 1;
32083213
}
32093214

32103215
void main()
32113216
{
3212-
Foo f;
3213-
int i = foo(&f.bar);
3217+
Foo f = {7};
3218+
int delegate() dg = &f.get; // bind to an instance of Foo and a method
3219+
assert(dg.ptr == &f);
3220+
assert(dg.funcptr == &Foo.get);
3221+
3222+
int i = add1(dg);
32143223
assert(i == 8);
32153224

32163225
int x = 27;
32173226
int abc() { return x; }
32183227

3219-
i = foo(&abc);
3228+
i = add1(&abc);
32203229
assert(i == 28);
32213230
}
32223231
------
32233232
)
32243233

3225-
$(P This combining of the environment and the function is called
3226-
a $(I dynamic closure).
3227-
)
3228-
32293234
$(P The $(D .ptr) property of a delegate will return the
32303235
$(I context pointer) value as a $(D void*).
32313236
)

0 commit comments

Comments
 (0)