Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The Box pointer is a unique pointer. It owns an object of type T that resides on the heap. A Box:

31.1.1Putting an object in a Box

Let us create a structure with many fields:

see solution

We add some methods to it:

We create an instance of Book:

Book { title: "Le Petit Prince", authors: ["Antoine de Saint-Exupéry"], isbn: 2070408507, year: 1999, editor: "Gallimard", npages: 104, price: 7.5, pitch: "J'ai ainsi vécu seul, sans personne avec qui parler véritablement, jusqu'à une panne dans le désert du Sahara, il y a six ans. Quelque chose ..." }

Now we move the Book instance into a Box struct:

Couldn't automatically determine type of variable `book`.
Please give it an explicit type.

The new book object, though being a Box, behaves like a plain Book object:

We can call Book methods on it:

31.1.2Size of a Box

The size of a Box depends on the stored type:

See Word to know what is a word.

31.1.3Passing a Box

Compared to the 120 bytes of our Book structure, the 8 bytes of the Box object is 15 times lighter. This seems like a huge improvement if we need to move often our object to functions.

For instance we could write the following function:

When calling it, we would pass it our light Box object that would be moved:

31.1.4Is Box really useful?

However the following function, that also involves a move would not be less performant:

This is because, in practice, there is no actual move of the object. The passed object, Book in one case, Box in the other, is not moved but resides in its place on the stack inside the caller’s frame. The callee only gets a pointer to the object inside the caller’s frame.

31.1.5Recursive type

The Box is also useful for defining recursive type. As an example we are going to create a chain List type as an enum. The type will be generic, and thus will be able to store any type of values.

Let us define it by making a recursive reference to the type itself. The following definition states that the Val variant contains a value and the next element, and that the Nil value marks the end of the list:

However an enum can only be defined if we can compute its size. The size of an enum is the size of its biggest variant. The size of the Val variant being impossible to compute, this enum definition is invalid, the compiler will reject it.

We must thus give a fixed size to the Val variant. The Box structure is exactly what we need. It will move the next element onto the heap, and it has a fixed size whatever the value it points to. Here is the new definition:

Let us import the enum’s variants to ease their use:

We implement a print() that we will use to print the content of a list:

We can now create a list of, for instance, 32-bit integers, and prints it: