适当的实例化& cocos2d-x中的内存管理 [英] proper instantiation & memory management in cocos2d-x

查看:141
本文介绍了适当的实例化& cocos2d-x中的内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找cocos2d-x的文档,但它似乎真的很糟糕,超出了基础。我理解我自己的类应该继承 CCObject 以能够使用(最初的可可) retain / release 机制,但我仍然困惑当你 new 时发生什么。 init 不会自动调用。是否可以从构造函数内部调用它?这单独保证我的对象将开始参考计数1?什么是 CC_SAFE_DELETE 和什么时候应该使用它? do release autorelease 工作完全像可可? CC_SYNTHESIZE ?我只需要看到一个正确编码类的例子(它的实例化/销毁)来理解我应该做什么,以免螺丝和留下内存泄漏。
谢谢。

I've been looking for documentation for cocos2d-x but it seems to be really really poor beyond the very basics. I understand that my own classes should inherit from CCObject to be able to use (originally cocoa's) retain/release mechanism, but I'm still confused about what happens when you new something. init is not called automatically. is it OK to call it from inside the constructor? does that alone guarantee that my object will start with a reference count of 1? what is CC_SAFE_DELETE and when should I use it? do release and autorelease work exactly like in cocoa? what about CC_SYNTHESIZE? I just need to see a properly coded class example (and it's instantiation/destruction) to understand what I'm supposed to do so as not to screw and leave memory leaks. thank you.

推荐答案

如果你看看CCObject类的代码,你会看到它的构造函数引用计数设置为1。因此,使用 new 创建对象是正确的。 Init不被调用,因为CCObject类没有这样的方法。通常我喜欢使用静态构造函数创建对象。 Smth like

If you will look to the code of CCObject class, you will see that in it's constructor reference count is set to 1 there. So, object creation with new is correct. Init is not called because CCObject class has no such a method. Usually I prefer to create objects using static constructor. Smth like

MyClass* MyClass::createInstance()
{
    MyClass* object = new MyClass();

    // you can create virtual init method
    // and call it here

    if( initWasSuccessful )
    {
        object->autorelease();
    }
    else
    {
        CC_SAFE_RELEASE_NULL(object);
    }
    return object;
}



<这个宏只是检查对象是否为NULL,以防止在尝试调用release方法时崩溃。

About all macroses like CC_SAFE_DELETE - you can find them in the code of cocos2dx. This macros just check if object is NULL to prevent crash on trying to call release method.

这篇关于适当的实例化&amp; cocos2d-x中的内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆