-Safety is a top priority for the Swift programming language. Swift code expects its caller to adhere to Swift’s type rules and Swift’s memory model, regardless of whether it’s called from Swift or C++. Thus, the C++ code that calls Swift should properly enforce Swift’s expected language contracts. Such enforcement is needed to minimize the risk of Swift behaving in an unexpected manner at run-time when it’s being called from C++, as such behavior could lead to buggy program behavior or crashes that a Swift programmer would not expect to see in their Swift code. This kind of enforcement does not prevent all possible issues though, as it does not change C++'s safety model. C++ is unsafe by default, and the user is able to use regular C++ pointers to write to memory as if they were using Swift's `UnsafeMutablePointer` type. This means that bugs in C++ code can easily lead to violations of Swift's expected invariants. For instance, a bug in user’s C++ code could accidentally overwrite a Swift object stored on the heap, which could cause unexpected behavior or crashes in Swift code. The user is expected to obey Swift's memory model and type rules when calling into Swift APIs from C++, and thus they bear the ultimate responsibility for avoiding bugs like this one. The user can use certain program analysis tools, such as Address Sanitizer, to help them catch bugs that violate Swift's memory model rules.
0 commit comments