gpt4 book ai didi

swift - 警告: Initialization of 'UnsafeBufferPointer' results in a dangling buffer pointer

转载 作者:行者123 更新时间:2023-12-03 09:15:39 26 4
gpt4 key购买 nike

在更新到Swift 5.2/Xcode 11.4之后,警告以下代码:

extension Data {

init<T>(from value: T) {
var value = value
let pointer = UnsafeBufferPointer(start: &value, count: 1)
self.init(buffer: pointer)
}

func to<T>(type: T.Type) -> T {
return self.withUnsafeBytes { $0.load(as: T.self) }
}
}

行上,让指针= UnsafeBufferPointer(开始:&value,计数:1)我得到了

Initialization of 'UnsafeBufferPointer' results in a dangling buffer pointer



我可以使用@silenceWarning,但这是肮脏的解决方案。也许我需要将指针存储在某个地方并在将来进行清理?

最佳答案

我也遇到了这些烦人的警告。

var str = "aaaaabbbbbccccc"
var num1 = 1
var num2 = 22

var data = Data()
// Initialization of 'UnsafeBufferPointer<String>' results in a dangling buffer pointer
data.append(UnsafeBufferPointer(start: &str, count: 1))
// Initialization of 'UnsafeBufferPointer<Int>' results in a dangling buffer pointer
data.append(UnsafeBufferPointer(start: &num1, count: 1))
// Initialization of 'UnsafeBufferPointer<Int>' results in a dangling buffer pointer
data.append(UnsafeBufferPointer(start: &num2, count: 1))

考虑到@greg的回答,我将 Data.append放入 withUnsafePointer的闭包中,它不再显示警告。

withUnsafePointer(to: &str) { data.append(UnsafeBufferPointer(start: $0, count: 1)) } // ok
withUnsafePointer(to: &num1) { data.append(UnsafeBufferPointer(start: $0, count: 1)) } // ok
withUnsafePointer(to: &num2) { data.append(UnsafeBufferPointer(start: $0, count: 1)) } // ok

这是扩展名

extension Data {
init<T>(value: T) {
self = withUnsafePointer(to: value) { (ptr: UnsafePointer<T>) -> Data in
return Data(buffer: UnsafeBufferPointer(start: ptr, count: 1))
}
}

mutating func append<T>(value: T) {
withUnsafePointer(to: value) { (ptr: UnsafePointer<T>) in
append(UnsafeBufferPointer(start: ptr, count: 1))
}
}
}

关于swift - 警告: Initialization of 'UnsafeBufferPointer<T>' results in a dangling buffer pointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60857760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com