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:
- SmartPtr is a smart pointer to a single object, meaning it takes ownership of a pointer and is responsible for freeing it.
- Copying a SmartPtr copies the pointed object too.
- SharedPtr is similar to SmartPtr except it can be shared among multiple owners and uses Reference Counting.
- Copying a SharedPtr makes a shared copy (increments reference count) – all copies share the same instance.
- Ptr is a dumb pointer to a single object or array, meaning it only references the pointer and does not take ownership.
- This is useful to explicitly indicate the pointer is owned elsewhere or to distinghuish from a static immutable data pointer
- Never assign (or copy construct from) a raw pointer to an Evo container unless it refers to static immutable data (ex: string literal) – see Sharing for an example
- Dumb pointers can also be moved with addition or subtraction
- Atomic version: AtomicPtr
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
int maint() {
*num = 1;
nums[0] = 1;
nums[1] = 2;
return 0;
}
- Detailed Example
struct Data {
int val;
};
if (ptr)
c.
out <<
"Val: " << ptr->val <<
NL;
}
int main() {
ptr->val = 1;
ptr[0].val = 1;
(*ptr).val = 1;
print(ptr);
{
ptr2 = ptr;
ptr2->val = 2;
print(ptr2);
}
print(ptr3);
return 0;
}
Output:
- 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
- Minimal low-level struct interface
- Not copyable
- Specialized for array pointers with AutoPtr<T[]>
FreePtr is similar to AutoPtr, but frees with C library free() – for pointers returned by malloc().