Skip to content

Ownership Memory Management

IsaacShelton edited this page Nov 13, 2022 · 3 revisions

Ownership Memory Management

Most standard components in the Adept standard library used ownership-based memory management.

With ownership-based memory management, memory is freed when its owner runs out of scope.

Passing Around Ownership

With some datatypes that use ownership-based memory management, ownership can be given away.

This is often done via a method named commit(), which maintains the validity of the original owner while transferring ownership. Another method used is named donate(), which does NOT maintain the validity of the original owner while transferring ownership.

Obtaining Ownership

With some datatypes that use ownership-based memory management, ownership can be obtained by constructing a new value or cloning an existing value.

Some datatypes have a method named clone(), which can be used to duplicate the datatype. Some datatypes also have a method named make(), which will make a value into a duplicate if it doesn't already have ownership.

Simple Implementation

Datatypes that use ownership-based memory management often use the 2.7/Ownership.adept enum to store an internal state indicating whether a value has responsibility over memory it has access to.

import cstdlib
import cstring
import Ownership

struct ScopedCString (s *ubyte, ownership Ownership) {
    func __defer__ {
        if this.ownership != Ownership::OWN, return
        delete this.s
    }
}

func scopedCString(s *ubyte, ownership Ownership) ScopedCString {
    c POD ScopedCString
    c.s = s
    c.ownership = ownership
    return c
}

func main {
    firstname ScopedCString = scopedCString('Isaac', Ownership::REFERENCE)
    lastname ScopedCString = scopedCString(strdup('Shelton'), Ownership::OWN)
}

Example Datatypes

Clone this wiki locally