Memory and Resources
Most values in a tiko program live where the compiler puts them: in the frame of the procedure that declares them, created when the declaration runs and destroyed when the block ends. That is the stack, and it needs no help from you. When a value has to outlive the block that made it, or its size is known only at run time, you ask for memory on the heap, and giving it back becomes your job.
type Counter
as int32 value
declare constructor( byval start as int32 )
declare destructor( )
end type
constructor Counter( byval start as int32 )
value = start
print " made"; value
end constructor
destructor Counter( )
print " gone"; value
end destructor
function MakeOnHeap( byval n as int32 ) as Counter ptr
dim onStack as Counter = Counter( n ) '' lives until end function
return new Counter( n * 10 ) '' lives until delete
end function
print "calling"
dim as Counter ptr kept = MakeOnHeap( 4 )
print "back, and the heap one is still here:"; kept->value
delete kept
print "done"
Output
calling
made 4
made 40
gone 4
back, and the heap one is still here: 40
gone 40
done
MakeOnHeap makes two Counters. onStack is a local: its destructor runs
at end function, which is why "gone 4" appears before the caller prints
anything. The one made with new lives on the heap, so it survives the
return, and the caller destroys it with delete when it has finished.
| Stack | Heap | |
|---|---|---|
| made by | dim, var, parameters | new, allocate |
| destroyed | at the end of its block, automatically | by delete or deallocate |
| reached through | its name | a pointer |
| a mistake looks like | rare | a leak, or a use after free |
The pages in this section, from raw to managed:
- Pointers:
ptr,@,*,->and pointer arithmetic. - new and delete: typed heap allocation.
- nullptr: the null pointer, and what
-exxdoes with it. - References:
byrefvariables and results. - Destructors and scope: cleanup that runs by itself.
- defer for cleanup: freeing on every way out.
- Non-copyable types: one owner for one resource.
- Shared pointers:
SharedPtrandWeakPtr.
Activities
- Remove the
delete keptline. Which line of output disappears? - Make
MakeOnHeapreturn@onStackinstead. Why is that wrong, even if it seems to work?