> For example, I have a for loop that keeps requesting a new pointer...
Unless you put that pointer in a structure which lives forever, it will be freed as soon as a loop finishes:
struct Foo { a: int, b: int }
impl Drop for Foo {
fn drop(&mut self) {
println!("Drop {:?}", *self);
}
}
fn foo(i: int) -> Foo {
println!("Creating Foo with {}", i);
Foo { a: i, b: 5}
}
fn do_thing(foo: &Foo) {
println!("\tdo thing {:?}", *foo);
}
fn do_other_thing(foo: &Foo) {
println!("\tdo other thing {:?}", *foo);
}
fn main() {
for i in range(0, 5) {
let a = box foo(i);
do_thing(a);
do_other_thing(a);
}
}
will print Creating Foo with 0
do thing Foo{a: 0, b: 5}
do other thing Foo{a: 0, b: 5}
Drop Foo{a: 0, b: 5}
Creating Foo with 1
do thing Foo{a: 1, b: 5}
do other thing Foo{a: 1, b: 5}
Drop Foo{a: 1, b: 5}
Creating Foo with 2
do thing Foo{a: 2, b: 5}
do other thing Foo{a: 2, b: 5}
Drop Foo{a: 2, b: 5}
Creating Foo with 3
do thing Foo{a: 3, b: 5}
do other thing Foo{a: 3, b: 5}
Drop Foo{a: 3, b: 5}
Creating Foo with 4
do thing Foo{a: 4, b: 5}
do other thing Foo{a: 4, b: 5}
Drop Foo{a: 4, b: 5}
(drop is ~equivalent to a C++ destructor)