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:
std::shared_ptr<Matrix4x4> m(new Matrix4x4);
The latest is better since it makes a single memory allocation:
std::shared_ptr<Matrix4x4> m = std::make_shared<Matrix4x4>(new Matrix4x4);
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:
typedef std::shared_ptr<MyClass> Ptr;
return std::shared_ptr<MyClass>(new MyClass());
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?