delete this?

Looking under the hood in cocos2d-x I found multiple “delete this” coding practices. That’s bad programming. An object should not be deleting itself - ever. Let its manager manage its existance. Here is an example:

bool CCTextureAtlas::initWithFile(const char * file, unsigned int capacity)
{
// retained in property
CCTexture2D *texture = CCTextureCache::sharedTextureCache()->addImage(file);

if (texture)
{
return initWithTexture(texture, capacity);
}
else {
CCLOG (“cocos2d: Could not open file: %s”, file);
delete this;
return NULL;
}
}

This code leads to a sloppy bug in code that relies on this method in CCAtlasNode.

Found in latest beta release.

The problem here is the object will be deleted twice when executing textureAtlasWithFile with file that can’t be loaded (in initWithFile and then in textureAtlasWithFile). I think this is just a mistype because init… methods return true of false, not NULL, and the common practice in cocos2d-x is deleting objects in case of error in static factory methods, not in init… methods.

PS And yes, I’ve found several places in cocos2d-x where it happens too. This is a bug of course and needs to be fixed.

And BTW

An object should not be deleting itself - ever
An object MUST delete itself whenever it is it’s area of concern - for example in CCObject::release(). There will be no ‘manager’ or something when we retain or release objects we create. This is the main purpose of CCObject - delete itself when reference count goes to 0.