Reputation: 96832
I'm wrapping a C library, and it has a standard sort of context object:
library_context* context = library_create_context();
And then using that you can create more objects:
library_object* object = library_create_object(context);
And destroy them both:
library_destroy_object(object);
library_destroy_context(context);
So I've wrapped this up in Rust structs:
struct Context {
raw_context: *mut library_context,
}
impl Context {
fn new() -> Context {
Context {
raw_context: unsafe { library_create_context() },
}
}
fn create_object(&mut self) -> Object {
Object {
raw_object: unsafe { library_create_object(self.raw_context) },
}
}
}
impl Drop for Context {
fn drop(&mut self) {
unsafe {
library_context_destroy(self.raw_context);
}
}
}
struct Object {
raw_object: *mut library_object,
}
impl Drop for Object {
fn drop(&mut self) {
unsafe {
library_object_destroy(self.raw_object);
}
}
}
So now I can do this, and it seems to work:
fn main() {
let mut ctx = Context::new();
let ob = ctx.create_object();
}
However, I can also do this:
fn main() {
let mut ctx = Context::new();
let ob = ctx.create_object();
drop(ctx);
do_something_with(ob);
}
I.e. the library context is destroyed before the objects it creates are.
Can I somehow use Rust's lifetime system to prevent the above code from compiling?
Upvotes: 4
Views: 667
Reputation: 431649
Yes, just use normal lifetimes:
#[derive(Debug)]
struct Context(u8);
impl Context {
fn new() -> Context {
Context(0)
}
fn create_object(&mut self) -> Object {
Object {
context: self,
raw_object: 1,
}
}
}
#[derive(Debug)]
struct Object<'a> {
context: &'a Context,
raw_object: u8,
}
fn main() {
let mut ctx = Context::new();
let ob = ctx.create_object();
drop(ctx);
println!("{:?}", ob);
}
This will fail with
error[E0505]: cannot move out of `ctx` because it is borrowed
--> src/main.rs:26:10
|
25 | let ob = ctx.create_object();
| --- borrow of `ctx` occurs here
26 | drop(ctx);
| ^^^ move out of `ctx` occurs here
Sometimes people like to use PhantomData
, but I'm not sure I see the benefit here:
fn create_object(&mut self) -> Object {
Object {
marker: PhantomData,
raw_object: 1,
}
}
#[derive(Debug)]
struct Object<'a> {
marker: PhantomData<&'a ()>,
raw_object: u8,
}
Upvotes: 6