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
Swift class types that are usable from C++ are available in their corresponding module namespace. They’re bridged over as a C++ class that stores a referenced counted pointer inside of it. Its initializers, methods and properties are exposed as members of the C++ class.
576
+
577
+
### Reference counting in C++
578
+
579
+
C++ class types that represent Swift classes perform automatic
580
+
reference counting (ARC) operations when the C++ value that represents
581
+
the reference to the Swift class is copied and destroyed.
582
+
583
+
For example, the following Swift class:
584
+
585
+
```swift
586
+
// Swift module 'People'.
587
+
classPerson {
588
+
let name: String
589
+
init(name: String) {
590
+
self.name= name
591
+
print("\(name) is being initialized")
592
+
}
593
+
deinit {
594
+
print("\(name) is being deinitialized")
595
+
}
596
+
}
597
+
598
+
funccreateRandomPerson() -> Person {
599
+
returnPerson(name: getRandomName())
600
+
}
601
+
```
602
+
603
+
Can be used from C++ with reference counting performed
604
+
automatically:
605
+
606
+
```c++
607
+
#include"People-Swift.h"
608
+
609
+
usingnamespacePeople;
610
+
611
+
voiddoSomething(Person p) {
612
+
...
613
+
}
614
+
615
+
void createAndUsePerson() {
616
+
Person p = createRandomPerson();
617
+
618
+
doSomething(p); // 'p' is copied. Person referenced by p is referenced twice.
619
+
// Destructor for copy of 'p' is called. Person referenced by p is referenced once.
620
+
621
+
// Destructor for 'p' gets called here. Person referenced by p is deallocated.
622
+
}
623
+
```
624
+
625
+
The Swift `Person` class instance that C++ variable `p` referenced gets deallocated
626
+
at the end of `createAndUsePerson` as the two C++ values that referenced it
627
+
inside of `createAndUsePerson` were destroyed.
628
+
573
629
## Accessing Properties In C++
574
630
575
631
Swift allows structures and classes to define stored and computed properties. Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value. The stored and the computed properties from Swift types are bridged over as getter `get...` and setter `set...` methods in C++. Setter methods are not marked as `const` and should only be invoked on non `const` instances of the bridged types.
0 commit comments