我正在阅读the code of rust-sdl2,并且有这个Texture
结构:
pub struct Texture<'r> {
raw: *mut sys::SDL_Texture,
_marker: PhantomData<&'r ()>,
}
我怎么知道
'r
的生命周期从何而来?
最佳答案
如果这样声明结构,那么Rust将能够自动确保内存安全:
pub struct Texture<'r> {
raw: &'r mut sys::SDL_Texture,
}
由于
SDL_Texture
是在Rust代码之外进行管理的,因此这是不可能的,因为需要原始指针。 Texture
上的生命周期可以在不安全的数据结构周围添加一个内存安全的抽象。装箱管理
Texture
的创建,并确保生存期始终“正确”。生命周期可确保纹理不会超过内部SDL_Texture
,后者仅由原始指针引用。除不安全的函数外,您无法自己创建
Texture
。如果要调用TextureCreator::raw_create_texture
,则必须自己满足该生的所有要求。相反,安全方法create_texture
构造Texture
,同时保证内存安全。create_texture
的类型签名为:pub fn create_texture<F>(
&self,
format: F,
access: TextureAccess,
width: u32,
height: u32,
) -> Result<Texture, TextureValueError>
where
F: Into<Option<PixelFormatEnum>>,
一些生命被遗忘了。根据Rust的lifetime elision rules,可以将其更明确地写为:
pub fn create_texture<'r, F>(
&'r self,
format: F,
access: TextureAccess,
width: u32,
height: u32,
) -> Result<Texture<'r>, TextureValueError>
where
F: Into<Option<PixelFormatEnum>>,
生命周期批注表示
self
和Texture
之间的引用依赖性。因此,不允许返回的Texture
超过TextureCreator
的生命周期。
关于rust - 我如何弄清楚命名生命的来源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60720881/