>>The memory will not leak however, eventually it must go out of scope and then it will be free.
Yes, if the function that called it lives for ever the point is perhaps moot, in an extreme case if it was called by 'main'.
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) let mut blah = ~MyStruct{x: 3, y: 4};
for i in range(0,100000000) {
blah = ~MyStruct{x: i + blah.x, y: i + blah.y};
}
println!("{} {}", blah.x, blah.y);
The memory usage didn't increase over time - the owned pointer frees when it gets reassigned.