Template std.typecons.borrow
Borrows the payload of SafeRefCounted
for use in fun
. Inferred as @safe
if fun
is @safe
and does not escape a reference to the payload.
The reference count will be incremented for the duration of the operation,
so destroying the last reference will not leave dangling references in
fun
.
template borrow(alias fun)
;
Contained Functions
Name | Description |
---|---|
borrow |
Parameters
Name | Description |
---|---|
fun | A callable accepting the payload either by value or by reference. |
refCount | The counted reference to the payload. |
Returns
The return value of fun
, if any. ref
in the return value will be
forwarded.
Issues
For yet unknown reason, code that uses this function with UFCS syntax
will not be inferred as @safe
. It will still compile if the code is
explicitly marked @safe
and nothing in fun
prevents that.
Example
This example can be marked @safe
with -preview=dip1000
.
auto rcInt = safeRefCounted(5);
writeln(rcInt .borrow!(theInt => theInt)); // 5
auto sameInt = rcInt;
writeln(sameInt .borrow!"a"); // 5
// using `ref` in the function
auto arr = [0, 1, 2, 3, 4, 5, 6];
sameInt .borrow!(ref (x) => arr[x]) = 10;
writeln(arr); // [0, 1, 2, 3, 4, 10, 6]
// modifying the payload via an alias
sameInt .borrow!"a*=2";
writeln(rcInt .borrow!"a"); // 10
Authors
Andrei Alexandrescu, Bartosz Milewski, Don Clugston, Shin Fujishiro, Kenji Hara