I have a global struct that stores my objects and has complicated behavior. Besides the data it has a global id-generator for objects. They need them for their work too.
use std::sync::{Arc, Mutex};
static mut system_ptr: *mut Box<System> = 0 as *mut Box<System>;
struct System {
data: Vec<Data>,
id_mutex: Arc<Mutex<u32>>,
}
impl System {
fn get_new_id() -> u32 {
unsafe {
let s = &mut *system_ptr;
let mut data = s.id_mutex.lock().unwrap();
*data += 1;
*data
}
}
}
I am initializing that struct like this now:
fn main() {
let s = System{data: Vec::new(), id_mutex: Arc::new(Mutex::new(0 as u32))};
let mut s_box = Box::new(s);
unsafe {
system_ptr = &mut s_box as *mut Box<System>;
}
// here I have some work with the initialized "System"
}
When I move initialization code from main()
to some function, the Box
is dropped and I have a "use after free" error and a crash.
I've tried to use &'static
but am not fluent enough with Rust's semantics for now, or it was bad idea.
Anyway, how can I move initialization of some Box
'ed memory (raw pointer) to a function or method?
Edit: This is not a question about singleton, it's about initialization of any heap variable. Matt, thanks for the right understanding!