Search code examples
c++memorycocos2d-xsmart-pointersdynamic-memory-allocation

What are the advantages of Cocos2d-x custom memory model?


As I recently began developing in Cocos2d, one of the first features that I found very peculiar was the Objective-C style autorelease pool memory model. In all my experience with c++, I have avoided using any form of dynamic memory allocation unless ABSOLUTELY necessary (which is actually very rare).

At first, I was puzzled as to why Cocos2D did not take advantage of safer alternatives for creating pointer objects (e.g. smart pointers), but then I came across this thread, which discussed the disadvantages of shared_ptr<class T> (the most significant of which was speed) over the current memory paradigm with respect to manual retain / release methods.

Then I thought, "why not simply allocate an object regularly and pass and store its reference when necessary?" I understand that it would be extremely time-consuming to port Cocos2d-x's entire memory system to a new paradigm, but in the long run isn't it worth using more stable idiomatic c++ code?

What it all comes down to is what are the advantages of the current memory model as opposed to regular object allocation?


Solution

  • Memory management in game engines is a very specific topic, especially if you want to keep your engine simple to use. If you'll take a look at the Unreal Engine 4 they've gone much more further in their memory management approach with generating a reflection code. Generally speaking it is possible to create a cocos2d-x game without ever explicitly calling retain or release. Those methods first of all used when you need to manually extend lifetime of the object to avoid deleting it and creating it again (caching).

    Shared pointers will make syntax much more complex and will cause extra difficulties with dynamic casts and binding pointers as arguments. And what is more important you will have to use a weak_ptr along with shared to avoid cross references which also will take extra effort.

    Basically shared_ptr is a reference counting technique like intrusive_ptr which can be more naturally integrated into cocos2d-x. And functions like addChild/removeChild in cocos are incrementing and decrementing counter of the child object, so these paradigms are not as diverse as may seem at the first glance.