Skip to content

Commit 823cbca

Browse files
committed
[cxx-interop] Add SWIFT_RETUNRS_(UN)RETAINED discussions to C++ interop docs
1 parent f7f870c commit 823cbca

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

documentation/cxx-interop/index.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1293,6 +1293,35 @@ If multiple base types have conflicting `retain` or `release` functions, the der
12931293
Note that this inference currently applies only to `SWIFT_SHARED_REFERENCE`.
12941294
It does not apply to types annotated with `SWIFT_IMMORTAL_REFERENCE` or `SWIFT_UNSAFE_REFERENCE`.
12951295

1296+
#### Calling conventions when returning Shared Reference Types from C++ to Swift
1297+
1298+
When C++ functions and methods return `SWIFT_SHARED_REFERENCE` types, it is necessary to specify the ownership of the returned value.
1299+
For this you should use the `SWIFT_RETURNS_RETAINED` and `SWIFT_RETURNS_UNRETAINED` annotations on functions and methods.
1300+
These annotations tell the Swift compiler whether the type is returned as `+1` (retained) or `+0` (unretained).
1301+
1302+
```c++
1303+
// Returns +1 ownership.
1304+
SharedObject* makeOwnedObject() SWIFT_RETURNS_RETAINED;
1305+
1306+
// Returns +0 ownership.
1307+
SharedObject* getUnOwnedObject() SWIFT_RETURNS_UNRETAINED;
1308+
```
1309+
1310+
These annotations are necessary to ensure that appropriate `retain`/`release` operations are inserted at the boundary:
1311+
1312+
```swift
1313+
let owned = makeOwnedObject()
1314+
owned.doSomething()
1315+
// `owned` is already at +1, so no further retain is needed here
1316+
1317+
let unOwned = getUnOwnedObject()
1318+
// Swift inserts a retain operation on `unowned` here to bring it to +1.
1319+
unOwned.doSomething()
1320+
```
1321+
1322+
Note that the Swift compiler will automatically infer the ownership conventons for Swift functions returning `SWIFT_SHARED_REFERENCE` types.
1323+
See [Exposing C++ Shared Reference Types back from Swift](#exposing-c-shared-reference-types-back-from-swift) for calling Swift functions returning `SWIFT_SHARED_REFERENCE` types from C++.
1324+
12961325
### Inheritance and Virtual Member Functions
12971326

12981327
Similar to value types, casting an instance of a derived reference type to a

0 commit comments

Comments
 (0)