> On Jun 27, 2016, at 3:35 PM, Dave Abrahams <dabrah...@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
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution