@@ -1725,24 +1725,6 @@ ref int gun(return ref int x) {
1725
1725
}
1726
1726
---
1727
1727
)
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
-
1746
1728
$(P Returning the address of a `ref` variable is also checked in `@safe` code.)
1747
1729
1748
1730
$(SPEC_RUNNABLE_EXAMPLE_FAIL
@@ -1833,6 +1815,52 @@ void uranus()
1833
1815
---
1834
1816
)
1835
1817
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
+
1836
1864
$(H3 $(LNAME2 scope-parameters, Scope Parameters))
1837
1865
1838
1866
$(P A `scope` parameter of reference type must not escape the function call
0 commit comments