Skip to content

Commit 5802dc2

Browse files
WalterBrightdlang-bot
authored andcommitted
improve ref function documentation
1 parent 9dc7885 commit 5802dc2

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

spec/function.dd

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -346,20 +346,44 @@ $(H2 $(LNAME2 nothrow-functions, Nothrow Functions))
346346

347347
$(H2 $(LNAME2 ref-functions, Ref Functions))
348348

349-
$(P Ref functions allow functions to return by reference.
350-
This is analogous to ref function parameters.
349+
$(P Ref functions allow functions to return by reference,
350+
meaning that the return value must be an lvalue, and
351+
the lvalue is returned, not the rvalue.
351352
)
352353

353354
---
354355
ref int foo()
355356
{
356-
auto p = new int;
357+
auto p = new int(2);
357358
return *p;
358359
}
359360
...
360-
foo() = 3; // reference returns can be lvalues
361+
int i = foo(); // i is set to 2
362+
foo() = 3; // reference returns can be lvalues
361363
---
362364

365+
$(P Returning a reference to an expired function context is not allowed.
366+
This includes local variables, temporaries and parameters that are part
367+
of an expired function context.
368+
)
369+
370+
---
371+
ref int sun()
372+
{
373+
int i;
374+
return i; // error, escaping a reference to local variable i
375+
}
376+
---
377+
378+
$(P A `ref` parameter may not be returned by `ref`.)
379+
---
380+
ref int moon(ref int i)
381+
{
382+
return i; // error
383+
}
384+
---
385+
386+
363387
$(H2 $(LNAME2 auto-functions, Auto Functions))
364388

365389
$(P Auto functions have their return type inferred from any

0 commit comments

Comments
 (0)