[swift-evolution] [Draft] UnsafeRawPointer API

Dave Abrahams dabrahams at apple.com
Mon Jun 27 21:17:08 CDT 2016



Sent from my moss-covered three-handled family gradunza

> On Jun 27, 2016, at 4:50 PM, Andrew Trick <atrick at apple.com> wrote:
> 
> 
>>> On Jun 27, 2016, at 4:27 PM, Andrew Trick via swift-evolution <swift-evolution at swift.org> wrote:
>>> 
>>> 
>>>> 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())
>> ```
Doesn't that presume alignment?

> And updated for the proposal's current syntax...
> 
> This is well-defined:
> ```
> ptrA = rawPtr.initialize(A.self, with: A())
> ptrA.deinitialize()
> ptrB = rawPtr.initialize(B.self, 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.
> 
> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160627/ce11ce48/attachment.html>


More information about the swift-evolution mailing list