[swift-evolution] [Draft] UnsafeRawPointer API

Andrew Trick atrick at apple.com
Tue Jun 28 16:17:41 CDT 2016

> On Jun 28, 2016, at 1:53 PM, Dmitri Gribenko <gribozavr at gmail.com> wrote:
> Hi Andy,
> Everything is clear now, thank you!
> On Tue, Jun 28, 2016 at 1:02 PM, Andrew Trick <atrick at apple.com> wrote:
>> Initializing via a typed pointer, in addition to changing the temporal memory state, also imposes a type on the allocated memory for the entire lifetime of the memory itself, from allocation to deallocation.
> I see.  Given that UnsafeMutablePoiner.initialize() has this very
> important difference in semantics, did you consider reflecting it in
> the name?  Something like '.bindTypeAndInitialize()' -- but I'm sure a
> better wording is possible.

Yes, I did consider that. I’m still open to it--maybe ‘.typedInitialize(with:). But...

(1) It’s awkward. The developer isn’t interested in binding the type at that point. It’s just a side effect of the way their unsafe pointer is being used.

(2) It would imply that the ‘.bindAndInitialize' entry point is the only way to bind the type of allocated memory. But once you have a typed pointer, it’s easy to initialize memory via a simple assignment:
ptrToA[0] = A() // where A is trivial
If ptrToA was in an uninitialized state, then that also binds the type.

Instead, I tried to focus on discouraging the unsafe pointer cast that leads to this situation. The important thing is that we have an alternate “safe” API so that most developers just don’t need to think about it. 

I think the best way to make this clear is through API comments and code examples. There are just a handful of UnsafePointer idioms that will be prevalent (Expected use cases) , and as long as people follow normal patterns with the proposed API, they’re unlikely to run afoul of the rules.

If the proposed API still isn’t safe enough, and developers are running into problems, then that calls for development of a pointer type safety sanitizer.


> Dmitri
> -- 
> main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
> (j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/

More information about the swift-evolution mailing list