gpt4 book ai didi

rust - 我如何弄清楚命名生命的来源?

转载 作者:行者123 更新时间:2023-12-03 11:41:25 25 4
gpt4 key购买 nike

我正在阅读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>>,

生命周期批注表示 selfTexture之间的引用依赖性。因此,不允许返回的 Texture超过 TextureCreator的生命周期。

关于rust - 我如何弄清楚命名生命的来源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60720881/

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