#Creating a 'static living Closure for a deletion system.

3 messages · Page 1 of 1 (latest)

eager furnace
#

Hello, I'm trying to figure out the best way to create a sort of deletion queue system in Rust. For context, I'm programming Vulkan and am therefore not able to use the borrow checker to automatically clean up Vulkan objects.

Take for instance this piece of pseudocode


struct stuff{
  device: Vulkan_Device;
  queue: Vec<Box<dyn Fn()>>
}

impl stuff{
fn stuff_func(&mut self){
  let vulkan_object = make_vulkan_object();
  self.queue.push(Box::new(|| {
    self.device.delete_vulkan_object(vulkan_object);
  }));

  // ERROR, the closure doesn't live long enough
}

fn delete_objects(&mut self){
  for object_del_func in self.queue{
    object_del_func();
  }
}

The problem is that I can't create a closure that can live long enough to reach the delete_objects method.
Now in C++, I could just use a lambda or std::bind but here I cannot.

How should I go about deleting unsafe objects in order?

#

Please note that due to the large number of objects, I cannot just manually delete everything in the delete_objects unless I want a method that would just slowly grow to hundreds of lines I all must ensure are in the correct order.

solar lintel
#

You can fix the self reference by taking it as a parameter in the function:

struct stuff {
    device: Vulkan_Device,
    queue: Vec<Box<dyn FnOnce(&mut Vulkan_Device)>>,
}

impl stuff {
    fn stuff_func(&mut self) {
        let vulkan_object = make_vulkan_object();
        self.queue.push(Box::new(|device| {
            device.delete_vulkan_object(vulkan_object);
        }));
    }
}

fn delete_objects(mut self) {
    for object_del_func in self.queue {
        object_del_func(&mut self.device);
    }
}
```Also `FnOnce` instead of `Fn` since it looks like it consumes `vulkan_object`.