For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).
alloc
def alloc[T: AnyType, //](layout: Layout[T], /) -> Allocation[T]
Allocates owned storage for layout.count() elements of T.
Returns an Allocation, an explicitly destroyed handle that bundles the
newly allocated storage with its Layout. The compiler then enforces that
the Allocation is destroyed on every path — by passing it to dealloc,
or by explicitly leaking it with unsafe_leak().
When size_of[T]() == 0, this function returns a sentinel value.
Example:
from std.memory.alloc import alloc, dealloc, Layout
var allocation = alloc(Layout[Int32](count=4))
var ptr = allocation.unsafe_ptr()
for i in range(4):
(ptr + i).init_pointee_move(i)
dealloc(allocation^)
Constraints:
size_of[T]() must be greater than zero. layout.count() must be
greater than zero.
Parameters:
- T (
AnyType): The type of the elements to allocate storage for.
Args:
- layout (
Layout[T]): Describes the number of elements and alignment of the allocation.
Returns:
Allocation[T]: An Allocation owning the newly allocated, uninitialized storage.