[swift-evolution] [Draft] UnsafeRawPointer API

Andrew Trick atrick at apple.com
Mon Jun 27 18:27:38 CDT 2016


> On Jun 27, 2016, at 3:35 PM, Dave Abrahams <dabrahams at apple.com> wrote:
> 
>> Casting from a raw pointer to a typed pointer is only more dangerous
>> than other raw pointer operations because it is the first step in this
>> sequence of operations, which is undefined:
>> 
>> ptrA = rawPtr.cast(to: UnsafePointer<A>.self)
>> ptrA.initialize(with: A())
>> ptrA.deinitialize()
>> 
>> ptrB = rawPtr.cast(to: UnsafePointer<B>.self)
>> ptrB.initialize(with: B())
> 
> But it's trivial to get undefined behavior without any of that.  Just:
> 
>  _ = rawPtr.load(UnsafePointer<NonTrivialType>.self)

That's another way to obtain a typed pointer, but by itself it is well defined.

This is an important point, so I want to make sure I’m getting it across.

The following code is well-defined:
```
ptrA = rawPtr.initialize(with: A())
ptrA.deinitialize()
ptrB = rawPtr.initialize(with: B())
```
The following code is undefined:
```
ptrA = rawPtr.cast(to: UnsafePointer<A>.self)
ptrA.initialize(with: A())
ptrA.deinitialize()
ptrB = rawPtr.cast(to: UnsafePointer<B>.self)
ptrB.initialize(with: B())
```
It is hard to spot the difference between the two styles without drawing attention to the unsafe cast.

I considered naming the cast `UnsafeRawPointer.bind<T>(to: T.Type)` to indicate that the allocated memory is being bound to a type for the entire duration of its allocation. But it's actually the call to `initialize` a typed pointer that binds the type.

-Andy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160627/4cc963ec/attachment.html>


More information about the swift-evolution mailing list