Hello, I have this idea that can make memory management more flexible and still zero cost
Here is the specs and example :
fn a() -> (String, String) {
(
String::from("Hello"),
String::from("Hello 2")
) until MyLifetime
}
fn a2() -> (String, String) {
(
String::from("Hello"),
String::from("Hello 2")
) until MyLifetime2
}
fn b() {
// the heap above can be freed together from any place
// if close for MyLifetime is not called yet or called 2 times, it will return compile time error
close MyLifetime;
close MyLifetime2;
}
It also supports struct
struct MyData {
val1: String until Mylifetime1
val2: String until Mylifetime2
}
fn a() {
let data = MyData { .... };
close MyLifetime1;
// atempt to use the already closed val1 returns compile time error
println!("{:?}", data.val1);
}
// can override lifetime
fn b() {
// all the individual lifetime is overriden to MyNewLifetime
let data = MyData {
....
} until MyNewLifetime;
}
fn c() {
close MyNewLifetime;
}
The name for the lifetime can be any name. The name is unique, if duplicated name is detected it will return compile time error. If a panoc happen, the close is automatically called. This feels more flexible than scope based lifetime
At first glance it looks like Arena, yeah the lifetime is like Arena, but can be used to any allocator not tied to Arena allocator. So it can use Global allocator that is suitable for general purpose like individual deallocation
And then Thread's at exit hook
let mut val = String::new() until MyLifetime3;
let handle = thread::spawn(|| {
val.push("Hello");
});
// the heap is automatically dropped after the thread finish
handle.at_exit(|| {
close MyLifetime3;
});
handle.join();
So no Arc is needed, it is all zero cost and has guarantee. If stack reference is used, the compiler already returns compile time error. The different with std::thread::scope is, it does not force to wait the thread. So the thread can run in background without blocking the main thread, and still has safety guarantee that all the heap it uses is cleaned after it finish