Safe/Smart References in C++

C++’ standard library now has utilities for Weak References, RAII, and Safe Pointers. But it relies on classes and function calls, which take up precious CPU cycles and push a bunch of data onto the call stack. Not to mention, the syntax is notoriously messy.

Whether by means of garbage collection or syntactic sugar, modern languages like Go come with many of these features built in. Wouldn’t it be nice to have something similar for C++?

I figured out a way to use pointers and arrays to allocate space for my values on the heap, and to create multiple references to those values that avoids use-after free, double-free, and dangling pointer problems. The outer array is the “original” reference to the allocated variable on the heap. Subsequent references are pointers to the outer array. When the heap variable is deleted, the inner array element is set to null, which results in all of the references getting ‘null’ values, too.

The best thing about it is that you don’t need to do any pointer magic yourself – just call the utility macros.

Here’s a link to the code. Scroll down to the main() function for example usage.

Leave a Comment