Skip to content

Commit 08c62b4

Browse files
committed
[cxx-interop] Add SWIFT_RETUNRS_(UN)RETAINED discussions to C++ interop docs
1 parent 4b5e860 commit 08c62b4

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

documentation/cxx-interop/index.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1255,6 +1255,30 @@ object.doSomething()
12551255
// `object` will be released here.
12561256
```
12571257

1258+
To specify the ownership of returned `SWIFT_SHARED_REFERENCE` types, use the `SWIFT_RETURNS_RETAINED` and `SWIFT_RETURNS_UNRETAINED` annotations on C++ functions and methods. These annotations tell the Swift compiler whether the type is returned as `+1` (retained) or `+0` (unretained). This is necessary to ensure that appropriate `retain`/`release` operations are inserted at the boundary:
1259+
1260+
```c++
1261+
// Returns +1 ownership; Swift will take responsibility for releasing it.
1262+
SharedObject* makeOwnedObject() SWIFT_RETURNS_RETAINED;
1263+
1264+
// Returns +0 ownership; the caller must ensure the object stays alive.
1265+
SharedObject* makeUnownedObject() SWIFT_RETURNS_UNRETAINED;
1266+
```
1267+
1268+
These ownership conventions are reflected naturally in Swift:
1269+
```swift
1270+
let owned = makeOwnedObject()
1271+
owned.doSomething()
1272+
// `owned` is automatically released when it goes out of scope
1273+
1274+
let unowned = makeUnownedObject()
1275+
unowned.doSomething()
1276+
// make sure `unowned` remains valid while in use
1277+
```
1278+
1279+
These ownership annotations are also supported in Objective-C or Objective-C++ functions that return C++ `SWIFT_SHARED_REFERENCE` types.
1280+
1281+
12581282
### Inheritance and Virtual Member Functions
12591283

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

0 commit comments

Comments
 (0)