[swift-evolution] [swift-users] Unsafe(Mutable)Pointer (suc)predecessor and advancedBy functions

Adrian Zubarev adrian.zubarev at devandartist.com
Thu May 26 14:05:00 CDT 2016


This is where it gets tricky.

When you create a chunk of memory using 'UnsafeMutablePointer.memory()' or 'alloc()', it's as if you are programming in C with 'malloc' and 'free'. The memory you create and the objects you put in that memory don't participate in ARC - the runtime will not track reference counts or automatically free the memory. The memory will live on forever unless you explicitly call 'dealloc()' later.
Check.

Using these APIs correctly is quite hard. If you're not careful you can leak memory (if you lose all pointers before you've had a chance to call dealloc), or access invalid memory (you called dealloc earlier, but somewhere else you later access that memory). In a lot of cases a good thing to do is to wrap your unsafe memory buffer inside a regular Swift class, only allow the buffer to be accessed or modified through that class, and have that class be responsible for deallocating the buffer when its deinit is called. This way, you tie the lifetime of that buffer to your Swift class and ARC handles the memory management for you.
Exactly what I’m doing right now. :) But I’m still a little afraid when using these types.



-- 
Adrian Zubarev
Sent with Airmail
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160526/d8104221/attachment.html>


More information about the swift-evolution mailing list