Game Development

Smart Pointer System

I’ve taken a liking to smart pointers lately. The overhead is negligible and it’s vastly easier than having to keep track of pointers all over the place.

I read a bit about the std smart pointer. I don’t understand why the articles on smart pointers are so long or complicated, or why the boost library made a smart pointer. To me this seems the easiest thing in the world. Perhaps I don’t understand all the issues involved?

Smart Object

Smart Pointer

To use it, just derive your class from RakSmartObj. When instantiating your class, assign the pointer to an instance of RakSmartPtr. When all instances of RakSmartPtr are deleted or assigned to 0, then the class instance is automatically deleted.

4 replies on “Smart Pointer System”

This code is so called intrusive ptr. It’s the simplest one from refcounted smart pointers, if you look into boost library, you’ll see that their class is just as simple as your is, though more extensible.

However, this approach has some problems:
1. You have to derive from base class – in order to share something simple you’ll have to wrap it into a class that’s derived from base
2. You can’t specify incomplete (forward-declared) class as a type, thus creating unnecessary include-dependencies
3. It is harder for people (in my experience) to use intrusive pointers than pointers with a separate refcount
4. You can’t make a weak pointer easily with intrusive ptr

The reasons why boost has smart pointer are:
1. No matter how simple the code is, it’s better to have a (more or less) standard component than to write a new one
2. It’s definitely not that simple if we’re talking about separate reference counts (shared_ptr in Boost). It’s not rocket science either, but again it’s much better to have a tested version instead of needing to write one.

As much as I don’t like Boost, smart pointers library is one of the best things in it in terms of implementation.

Thanks for the clarification! Not being able to do forward declarations of pointers is a major drawback.

I read about their system and here’s the summary as I understand it

scoped_ptr is fast. If the pointer goes out of scope, the object is deleted. If the object is deleted, the pointer is set to null. Cannot point to arrays.

scoped_array same as scoped_ptr, but for arrays

shared_ptr is like what I have, but you can have incomplete types and don’t have to have your class derive from anything. Cannot point to arrays.

shared_array is like shared_ptr for arrays

weak_ptr is a pointer that will be set to null if the object is deleted, but won’t delete the object itself when the pointer goes out of scope. Also used if shared_ptr would result in cycles

intrusive_ptr like what I have.

Leave a Reply

Your email address will not be published. Required fields are marked *