v0.4.0
Memory · Lesson 15.10

Box

Source
Own one allocated value with Box<T>, which destroys the value and returns its memory when the box's life ends.

The raw lessons kept leaving one job to you: remember to give the memory back, exactly once, and never touch it afterwards. A Box<T> takes that job over. It owns one value that lives in allocated memory, and — like any value with a destructor — it cleans up after itself when its life ends.

Creating a box

Box::TryCreate<T>(allocator, value) asks the allocator for room, moves the value in, and hands back the box:

let boxed = try Box::TryCreate<Tally>(allocator, Tally { name: name, count: 1 });

Asking can fail, so TryCreate is declared -> Self throws AllocError, and try passes a refusal on. From this line on, the box is the value's one owner. Its sibling, Box<T>(allocator, value), does the same but treats running out of memory as fatal, as a String does, so it needs no try.

Reaching the value

Get() lends the value where it sits, as a &T?; GetMutable() lends it for writing, as a &var T?. Either is none only for a box whose value Take has moved out, so the program opens the optional with is:

if apples.GetMutable() is .Some(tally) {
    tally.count += 2;
}
if apples.Get() is .Some(tally) {
    PrintLine("    {} {}", tally.count, tally.name);
}

These are references, not raw pointers, so no unsafe is needed: the compiler checks them. While a reference from the box is in use, the box stays borrowed, and it cannot be moved or destroyed under it.

The box cleans up

Nobody calls Deallocate in this program. When a box's life ends, its destructor destroys the value — which runs ~Tally and prints a line — and then gives the memory back to the allocator it came from:

flowchart LR
    create["`Box::TryCreate(allocator, value)`"] --> alloc["the allocator gives room,<br/>the value moves in"]
    alloc --> use["`boxed.Get()` — use it"]
    use --> end_["the box's life ends"]
    end_ --> drop["`~Tally` runs"]
    drop --> back["memory goes back to<br/>the same allocator"]

You can see the timing in the output. The box in Count dies when Count returns, so destroying the pears tally is printed before Main carries on with a box in Main:.

Moving a box

A box cannot be copied: two owners would both release the memory, and the second release would hit memory that was no longer theirs. It can be moved, which hands the ownership on and retires the old name:

let storage = if apples.Get() is .Some(tally) { Address(tally) } else { 0 };
let owner = move apples;
let moved = if owner.Get() is .Some(tally) { Address(tally) } else { 0 };
PrintLine("    moved, same storage: {}", moved == storage);

Address turns where the tally's count lives into a plain number. Only the number is kept across the move: holding on to the reference itself would keep apples borrowed and forbid the move.

The value itself stays where it was allocated, so the new owner reaches the very same storage — the comparison prints true. Only the right to release it has moved. At the end of Main, owner releases the memory, once, and apples releases nothing because it no longer owns anything.

You writeWhat happens
let owner = move apples;ownership moves; apples can no longer be used
let owner = apples;rejected — a box cannot be copied
apples.Get()a borrowed &T?, keeping the box borrowed while used

The program

The whole lesson is one package in the Examples repository. Its comments explain every step.

Src/Main.rux
// A `Box<T>` owns one value that lives in allocated memory. `Box::TryCreate<T>(allocator, value)`
// asks the allocator for room, moves the value in, and hands back the box, or throws an
// `AllocError` if there was no room. (`Box<T>(allocator, value)` does the same but treats running
// out of memory as fatal.) From then on the box is the value's one owner.
//
// That ownership is what the raw lessons were missing. Nobody calls `Deallocate`: when the box's
// life ends, its destructor destroys the value and gives the memory back to the allocator it
// came from. And a box cannot be copied, because two owners would release the memory twice.
// Hand it on with `move`, and the old binding can no longer be used.
//
// `Get()` lends the value where it sits as a `&T?`, and `GetMutable()` as a `&var T?`; either is
// `none` only for a box whose value `Take` moved out. While the reference is in use the box stays
// borrowed, so it cannot be moved or destroyed under it.
import Allocator::{ AllocError, Allocator, Box, SystemAllocator };
import Io::PrintLine;

struct Tally {
    name: char8[..];
    count: int;
}

extend Tally {
    func ~Tally(&var self) {
        PrintLine("    destroying the {} tally", self.name);
    }
}

// The box is created and dies inside this call, so its memory is returned before `Main` resumes.
func Count(allocator: Allocator, name: char8[..]) throws AllocError {
    let boxed = try Box::TryCreate<Tally>(allocator, Tally { name: name, count: 1 });
    if boxed.Get() is .Some(tally) {
        PrintLine("    counted {} {}", tally.count, tally.name);
    }
}

// Where a tally's count lives in memory, which changes only if the tally itself is moved.
func Address(tally: &Tally) -> uint {
    return @tally.count as uint;
}

func Main() throws AllocError {
    let allocator = SystemAllocator();

    PrintLine("a short-lived box:");
    try Count(allocator, "pears");

    PrintLine("a box in Main:");
    var apples = try Box::TryCreate<Tally>(allocator, Tally { name: "apples", count: 3 });
    if apples.GetMutable() is .Some(tally) {
        tally.count += 2;
    }
    if apples.Get() is .Some(tally) {
        PrintLine("    {} {}", tally.count, tally.name);
    }

    // Moving the box moves the ownership. The value itself stays where it was allocated, so the
    // new owner points at the very same storage. Only the address is kept across the move, as a
    // number: a reference would keep `apples` borrowed and forbid the move.
    let storage = if apples.Get() is .Some(tally) { Address(tally) } else { 0 };
    let owner = move apples;
    let moved = if owner.Get() is .Some(tally) { Address(tally) } else { 0 };
    PrintLine("    moved, same storage: {}", moved == storage);

    // Using `apples` from here on is rejected: it was moved out. `owner` releases the memory, once.
    PrintLine("end of Main:");
}

Besides Io, its Rux.toml lists Allocator under [Dependencies].

Run it

cd Examples/Memory/Box
rux run
a short-lived box:
    counted 1 pears
    destroying the pears tally
a box in Main:
    5 apples
    moved, same storage: true
end of Main:
    destroying the apples tally

Common mistakes

Try it yourself

  1. Create a second box, plums, in Main before apples. Predict the order of the two destroying lines at the end, then run.
  2. Write func Report(owner: Box<Tally>) that prints the tally, and call it as Report(move apples). Where does destroying the apples tally appear now?
  3. Change Count to return the box, -> Box<Tally> throws AllocError, with return move boxed;, and keep it alive in Main.
  4. Call apples.Take() and print the tally it hands back. What does apples.Get() answer afterwards?

Learn more

  • Move and Destructor — the ownership rules a box is built on
  • Allocator — where a box's memory comes from
  • Arena — an allocator a box can draw from, with one extra rule