What I like about C++ 2011

C++ 2011, AKA C++0x, is the new version of what is maybe considered as the king of programming languages. I was a C++ programmer before I ever became a Flash developer. But what I truly love about this new version of C++ is how it makes a lot of things simpler without sacrifying performances.

So this will be the first post in a series to detail what I like about C++ 2011. One of the new things I like the most are shared pointers.

Handling memory properly has always been a problem in non managed languages. The garbage collector performance impact is debatable (and a very complicated debate indeed), but when you’re working with C++ that’s out of the question anyway. You have to allocate memory with “new” and release it with “delete”.

For quite some time now libraries such as Boost provided what was commonly called “smart pointers”. This concept is now part of the C++ STL with the std::shared_ptr class, AKA “shared pointers”. The idea is simple: shared pointers will store a reference counter and delete the actual pointer it holds whenever that counter goes to 0.

Working with shared pointers is just as easy as creating an std::shared_ptr object and passing a pre-allocated pointer or even better using the std::make_shared:

The latest is better since it makes a single memory allocation:

As an API developer, it makes it a lot easier for me to provide a clean API that will enforce an efficient memory management. Sure, shared pointers have a little overhead. The general consensus is a 5% memory/CPU hit in the worst cases. Working with references or leveraging copy elision should make things easier. Still, that’s a little price to pay for a 0% memory leak performance!

If you chose to, you can even force your users to use only shared pointers by making the constructor private:

Whether that constructor should really be private or users simply incentivized to use the create() method is something I have not firmly decided yet. The first solution is a very strong statement: I don’t want you to deal with my memory. The second one is more flexible: I give you the choice to crash everything.

What do you think?

  • Marwan Burelle

    C++11 shared pointers are nice, but I think they get it wrong when they decide to make the ref-counter mandatory (the counter is visible in the api). It prevents a good and efficient lock-free implementation … (Shared pointers could have been implemented using hazard pointers … )

  • Pingback: From ActionScript 3 to C++ 2011 | Jean-Marc Le Roux()