swift – 如果一个函数返回一个UnsafeMutablePointer是我们的责任销毁和dealloc?

前端之家收集整理的这篇文章主要介绍了swift – 如果一个函数返回一个UnsafeMutablePointer是我们的责任销毁和dealloc?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
例如,如果我要写这个代码
var t = time_t()
time(&t)
let x = localtime(&t) // returns UnsafeMutablePointer<tm>

println("\(x.memory.tm_hour): \(x.memory.tm_min): \(x.memory.tm_sec)")

…还有必要还要做以下几件事吗?

x.destroy()
x.dealloc(1)

还是没有分配内存,所以不需要解除它?

更新#1:

如果我们想象一个返回UnsafeMutablePointer的函数

func point() -> UnsafeMutablePointer<String> {
    let a = UnsafeMutablePointer<String>.alloc(1)
    a.initialize("Hello,world!")
    return a
}

调用函数将导致一个对象的指针,永远不会被破坏,除非我们自己做肮脏的工作.

我在这里问的问题是:从localtime()调用中收到的指针是否有任何不同?
模拟器和操场都使我们能够向返回的指针发送一个dealloc(1)调用,但是我们应该这样做还是稍后通过其他方法对返回的指针进行释放?

目前我错误地认为我们确实需要销毁和释放.

更新#1.1:

最后一个假设是错误的.我不需要释放,因为我没有创建对象.

更新#2:

我在Apple开发论坛上收到了同样的查询some answers.

In general,the answer to your question is yes. If you receive a pointer to memory which you would be responsible for freeing in C,then you are still responsible for freeing it when calling from swift … [But] in this particular case you need do nothing. (JQ)

the routine itself maintains static memory for the result and you do not need to free them. (it would probably be a “bad thing” if you did) … In general,you cannot know if you need to free up something pointed to by an UnsafePointer…. it depends on where that pointer obtains its value. (ST)

UnsafePointer’s dealloc() is not compatible with free(). Pair alloc() with dealloc() and malloc and co. with free(). As pointed out prevIoUsly,the function you’re calling should tell you whether it’s your response to free the result … destroy() is only necessary if you have non-trivial content* in the memory referred to by the pointer,such as a strong reference or a Swift struct or enum. In general,if it came from C,you probably don’t need to destroy() it. (In fact,you probably shouldn’t destroy() it,because it wasn’t initialized by Swift.) … * “non-trivial content” is not an official Swift term. I’m using it by analogy with the C++ notion of “trivially copyable” (though not necessarily “trivial”). (STE)

最后更新:

我现在写了一个博客文章,概述了关于发布StackOverflow,Apple Dev Forums,Twitter以及Apple关于分配内存和释放ARC的旧文档的不安全指针的发现和假设.见here.

来自Swift库UnsafeMutablePointer< T>

A pointer to an object of type T. This type provides no automated
memory management,and therefore the user must take care to allocate
and free memory appropriately
.

指针可以处于以下状态之一:

>没有分配内存(例如,指针为空,或内存为空
以前被释放);
>内存被分配,但是值尚未初始化;
>分配内存,并初始化值.

struct UnsafeMutablePointer<T> : RandomAccessIndexType,Hashable,NilLiteralConvertible { /**/}

猜你在找的Swift相关文章