I had code which looked almost exactly what you were doing and was getting the same warning. Mine differed slightly in a way which is relevant to the discussion
init<T>(from value: T) {
var value = value
self.init(buffer: UnsafeBufferPointer(start: &value, count: 1))
}
This still generates the warning that UnsafeBufferPointer is producing a dangling Pointer but the hints say "produces a pointer valid only for the duration of the call to 'init(start:count:)'"
But the return from UnsafeBufferPointer isn't assigned to anything, so I couldn't use it outside the scope of the init if I tried. So the compiler here is warning me against doing something I can't do anyway.
I guess Data.init(buffer: ) could be storing the ptr, but I would assume that if it accepts an UnsafeBufferPointer, it's accepting the responsibility for using it properly
Anyway, that still doesn't really fix your problem. I got around the warning with this
init<T>(from value: T) {
var value = value
var myData = Data()
withUnsafePointer(to:&value, { (ptr: UnsafePointer<T>) -> Void in
myData = Data( buffer: UnsafeBufferPointer(start: ptr, count: 1))
})
self.init(myData)
}
And this does not generate the warning and appears to work (in my application anyway). Whether it passes muster with the experts here is another matter.
Kind of makes me nostalgic for the days of HLock and HUnlock