[swift-evolution] [Draft] UnsafeRawPointer API
dabrahams at apple.com
Mon Jun 27 21:15:53 CDT 2016
Sent from my moss-covered three-handled family gradunza
> On Jun 27, 2016, at 4:27 PM, Andrew Trick <atrick at apple.com> 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())
>>> 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.
Sorry, I meant to dereference that typed pointer as part of the expression. Now boom.
> 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())
> ptrB = rawPtr.initialize(with: B())
> The following code is undefined:
> ptrA = rawPtr.cast(to: UnsafePointer<A>.self)
> ptrA.initialize(with: A())
> 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.
How is that substantially different from my example?
> 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...
More information about the swift-evolution