You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Now that `SharedObject` is imported as a reference type in Swift, the programmer will be able to use it in the following manner:
1252
1252
```swift
1253
-
// Call the C++ constructor of SharedObject using Swift initializer syntax.
1254
-
let object = SharedObject()
1255
-
object.doSomething()
1253
+
// The C++ constructor is imported as a Swift initializer
1254
+
let object1 = SharedObject.create()
1255
+
let object2 = SharedObject()
1256
+
object1.doSomething()
1257
+
object2.doSomething()
1256
1258
// `object` will be released here.
1257
1259
```
1258
1260
1259
-
You can create instances of `SharedObject` directly in Swift by calling its C++ constructor through a Swift initializer.
1261
+
You can create instances of `SharedObject` directly from Swift by calling its C++ constructor through a Swift initializer.
1262
+
1263
+
**NOTE:** Swift uses *default*`new` operator for constructing c++ shared reference types. If you'd like to prevent Swift from importing constructors as initializers, you can also delete the *default*`new` operator in C++.
1264
+
1265
+
1266
+
Alternatively, you can also construct instances of `SharedObject` using a user-defined static factory function, provided that the factory function is annotated with `SWIFT_NAME("init(...)")`, where the number of `_` placeholders matches the number of parameters in the factory function.
1267
+
1268
+
For example, consider a factory that performs custom allocation or returns a singleton instance:
In this case, Swift will import the static `make` function as a Swift initializer:
1260
1279
1261
-
Alternatively, you can construct instances using a user-defined static factory function, provided that the factory function is annotated with `SWIFT_NAME("init(...)")`, where the number of `_` placeholders matches the number of parameters in the factory function
1280
+
```swift
1281
+
let object = SharedObject(id: 42)
1282
+
object.doSomething()
1283
+
```
1262
1284
1263
-
> **Note**: If a C++ constructor and a user-annotated staticfactory (via `SWIFT_NAME`) have identical parameter signatures, Swift prefers the static factory when resolving initializer calls.
1285
+
**Note**: If a C++ constructor and a user-annotated static factory (via `SWIFT_NAME`) have identical parameter signatures, Swift prefers the static factory when resolving initializer calls. Using `SWIFT_NAME("init(...)")` is especially useful if you want to use a custom allocator or you want to disable direct construction entirely and expose only factories.
0 commit comments