“Smart” pointers

During my vacation I’ve been drawing pixel art for my next game and brainstormed around some basic game structure. Creating pixel graphics is consuming a lot of time.  In round terms it takes at least 5 hours (for me, the newb)  to get a very simple enemy ship done. And that requires that I’ve sketched some ideas first. I also had some time structuring some game logic for the next game. This article will be about the “dangerously easy” in coding.

Smart pointers

Smart pointers is the “magic bullet” in C++11. If you recall, I’ve been nagging about how tedious it is to keep track on the memory allocation in C++? Smart pointer is supposed to be the supreme solution to this problem, since it auto-magically releases the memory for you.

Smart pointers are actually template wrapped pointers which frees the allocation, when the object is supposed to be dead.  However, there are three commonly used types of smart pointers. They’re called unique_ptr, shared_ptr and weak_ptr.

So I though “Wow, this would be neat to implement in the next game so I can spare some time hunting memory leaks.”. I started straight away to play around with the new types of pointers. And I’ll try to go through them in my ever so “not knowing much about smart pointers” manner.

My first assumption was that smart pointer was treated as regular pointer per type (like MyObject*). But no, you need to specify what kind of smart pointer you’re using and the type of the object…

A unique pointer refers that it has one specific owner. While been using raw pointers before I pretty much used them as reference. Thrown them into functions and everything was fine and dandy. Although this use of unique_ptr soon gets to a halt. Consider the code below:

The code above won’t compile. Since it tries to destroy the object when it goes out of scope. What you can do is to pass your unique pointer as a reference. So then I turned to:


Shared pointers sounded good to me. Most of my time programming I’ve been coding web applications in PHP, where all objects you pass around are passed by reference. This is very convenient. Shared pointers “kind of” works in the same manner. It has a reference counter. When the shared_ptr doesn’t have any references left it self destructs. This is also pretty much how it seems to work in Obj-C. Of course this convenient solution has been questioned and “use in worst case” like here.


So if I wasn’t confused enough, there is of course a third type of smart pointer called weak_ptr, of which I haven’t tried to read up much on. I suspect its a type of a shared_ptr?


I’m still a bit confuse, but I’ll try implementing smart pointers in the new game, hopefully I don’t have to rewrite everything when I’m done…

Leave a Reply

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


This site uses Akismet to reduce spam. Learn how your comment data is processed.