I’ve got one more question that bothers me.

Lets say I’ve got a class that might look something like this:

class Reference {
     
    var pointer: UnsafeMutablePointer<Int>
     
    init(integer: Int) {
        self.pointer = UnsafeMutablePointer<Int>.alloc(1)
        self.pointer.initialize(integer)
    }
     
    deinit {
        self.pointer.destroy(1)
        self.pointer.dealloc(1)
    }
}
Let talk about ARC here. If I use optionals here and release manually the 
reference deinit will be called and we’re happy here:

var reference: Reference? = Reference(integer: 123456789)
reference = nil
If I don’t use optionals because I want my value to exist while the application 
is running, deinit will never be called but my application terminates just fine 
(SIGKILL?):

let reference = Reference(integer: 123456789)
Doesn’t this create a memory leak?

How do I solve this problem, especially if don’t know whats inside the 
Reference type (assume I’m a different developer who only has access to the 
framework but not its implementation)?



-- 
Adrian Zubarev
Sent with Airmail

Am 23. Mai 2016 um 18:31:43, Jordan Rose (jordan_r...@apple.com) schrieb:


On May 21, 2016, at 01:48, Adrian Zubarev via swift-users 
<swift-users@swift.org> wrote:

I played around with UnsafeMutablePointer and realized one behavior:

let pString = UnsafeMutablePointer<String>.alloc(1)
pString.initialize("test")
pString.predecessor().memory // will crash ax expected
pString.predecessor() == pString.advancedBy(-1) // true
pString.destroy()
pString.dealloc(1)

where

let iInt = UnsafeMutablePointer<String>.alloc(1)
iInt.initialize("test")
iInt.predecessor().memory // will not crash
iInt.predecessor() == iInt.advancedBy(-1) // true
iInt.predecessor().memory = 42 // did I just modified some memory I don't own?
iInt.destroy()
iInt.dealloc(1)

Is this intended? This is really the case where its unsafe.


Dmitri’s answers are all better for this specific discussion, but in general, 
“unsafe” in Swift means “if you don’t follow the rules, this may crash, may 
silently corrupt memory or do other bad things, may cause other code to be 
optimized out or miscompiled, may be harmless”. In this particular case, it’d 
be hard to check for the validity of the pointer while also being fast and 
binary-compatible with C.

Jordan

_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to