Skip to content

Commit 56a5066

Browse files
authored
[spec/function] Document return parameters without scope (#3619)
Part of Issue 17934 - [scope] scopeness entrypoint for unique/ref-counted missing. Add 'Struct Return Methods' subheading.
1 parent 14b0998 commit 56a5066

File tree

1 file changed

+46
-18
lines changed

1 file changed

+46
-18
lines changed

spec/function.dd

Lines changed: 46 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1725,24 +1725,6 @@ ref int gun(return ref int x) {
17251725
}
17261726
---
17271727
)
1728-
$(P Struct non-static methods marked with the `return` attribute ensure the returned
1729-
reference will not outlive the struct instance.
1730-
)
1731-
1732-
---
1733-
struct S
1734-
{
1735-
private int x;
1736-
ref int get() return { return x; }
1737-
}
1738-
1739-
ref int escape()
1740-
{
1741-
S s;
1742-
return s.get(); // Error: escaping reference to local variable s
1743-
}
1744-
---
1745-
17461728
$(P Returning the address of a `ref` variable is also checked in `@safe` code.)
17471729

17481730
$(SPEC_RUNNABLE_EXAMPLE_FAIL
@@ -1833,6 +1815,52 @@ void uranus()
18331815
---
18341816
)
18351817

1818+
$(H4 $(LNAME2 struct-return-methods, Struct Return Methods))
1819+
1820+
$(P Struct non-static methods can be marked with the `return` attribute to ensure a returned
1821+
reference will not outlive the struct instance.
1822+
)
1823+
1824+
$(SPEC_RUNNABLE_EXAMPLE_FAIL
1825+
---
1826+
struct S
1827+
{
1828+
private int x;
1829+
ref int get() return { return x; }
1830+
}
1831+
1832+
ref int escape()
1833+
{
1834+
S s;
1835+
return s.get(); // Error: escaping reference to local variable s
1836+
}
1837+
---
1838+
)
1839+
$(P The hidden `this` ref-parameter then becomes `return ref`.)
1840+
1841+
$(P The `return` attribute can also be used to limit
1842+
the lifetime of the returned value, even when the method is not `ref`:
1843+
)
1844+
1845+
---
1846+
struct S
1847+
{
1848+
private int i;
1849+
int* get() return @safe => &i;
1850+
}
1851+
1852+
void f() @safe
1853+
{
1854+
int* p;
1855+
{
1856+
S s;
1857+
int *q = s.get(); // OK, q has shorter lifetime than s
1858+
p = s.get(); // error, p has longer lifetime
1859+
p = (new S).get(); // OK, heap allocated S
1860+
}
1861+
}
1862+
---
1863+
18361864
$(H3 $(LNAME2 scope-parameters, Scope Parameters))
18371865

18381866
$(P A `scope` parameter of reference type must not escape the function call

0 commit comments

Comments
 (0)