Evo C++ Library v0.5.1
Managed Pointers

A managed pointer is a class that emulates a raw (built-in) pointer type.

Using managed pointers makes the intent and ownership of the pointer clear and reduces risk of pointer misuse and memory bugs.

Managed pointers:

All managed pointers are specialized for array types (T[]) to use delete[] to free memory (when applicable). Managed array pointers can't make a copy of the pointed objects (array size not known).

Managed pointers should be used instead of raw pointers as much as possible. Dereference operators (operator*, operator->, operator[]) are overloaded so they work like raw pointers.

Quick Example
#include <evo/ptr.h>
using namespace evo;
int maint() {
// Smart pointer to int
SmartPtr<int> num(new int);
*num = 1;
// Smart pointer to int array
SmartPtr<int[]> nums(new int[2]);
nums[0] = 1;
nums[1] = 2;
return 0;
}
Detailed Example
#include <evo/ptr.h>
#include <evo/io.h>
using namespace evo;
static Console& c = con();
// Example class/object
struct Data {
int val;
};
// Uses dumb Ptr so it's clear this function does not take pointer ownership
void print(Ptr<Data> ptr) {
if (ptr) // evaluate managed pointers as bool for easy not-null check (uses SafeBool)
c.out << "Val: " << ptr->val << NL;
}
int main() {
// Smart pointer
SmartPtr<Data> ptr(new Data);
// Set a value, dereference like normal pointer (3 different examples here)
ptr->val = 1;
ptr[0].val = 1;
(*ptr).val = 1;
// Pass pointer to a function
print(ptr);
// New scope, use dumb pointer, change value
{
// Dumb pointer referencing ptr
Ptr<Data> ptr2;
ptr2 = ptr;
// Change value, pass to function
ptr2->val = 2;
print(ptr2);
}
// Transfer ownership for fun
SmartPtr<Data> ptr2(ptr.detach());
// Get a raw pointer for fun, pass to function
Data* ptr3 = ptr2.ptr();
print(ptr3);
return 0;
} // ptr is null, ptr2 automatically freed

Output:

Val: 1
Val: 2
Val: 2
Low-Level Auto-Pointers

AutoPtr is a minimal stripped down version of SmartPtr, mainly used internally to make code exception/leak safe without a dependency on SmartPtr

FreePtr is similar to AutoPtr, but frees with C library free() – for pointers returned by malloc().