cocos2d x 3.3rc2 002 cocos里的c 两段构造 - cheyiliu/All-in-One GitHub Wiki
- 示例代码
Scene* HelloWorld::scene() { // 'scene' is an autorelease object auto scene = Scene::create(); // scene不是通过new出来的
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create(); // layer不是通过new出来的
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
Scene* Scene::create() { Scene *ret = new (std::nothrow) Scene(); if (ret && ret->init()) { ret->autorelease(); return ret; } else { CC_SAFE_DELETE(ret); return nullptr; } }
* 相关宏提供的保障
/**
- define a create function for a specific type, such as Layer
- @param _TYPE_ class type to add create(), such as Layer
/
#define CREATE_FUNC(TYPE)
static TYPE create()
{
TYPE *pRet = new TYPE();
if (pRet && pRet->init())
{
pRet->autorelease();
return pRet;
}
else
{
delete pRet;
pRet = NULL;
return NULL;
}
}
/**
- define a node function for a specific type, such as Layer
- @param _TYPE_ class type to add node(), such as Layer
- @deprecated This interface will be deprecated sooner or later.
/
#define NODE_FUNC(TYPE)
CC_DEPRECATED_ATTRIBUTE static TYPE node()
{
TYPE *pRet = new TYPE();
if (pRet && pRet->init())
{
pRet->autorelease();
return pRet;
}
else
{
delete pRet;
pRet = NULL;
return NULL;
}
}
// 构造函数的可见性protected, 定义见cocos/base/ccConfig.h 这保证了cocos的相关类不能通过new来实例化对象 CC_CONSTRUCTOR_ACCESS:// protected Layer();// Node等构造函数的可见性
/** @def CC_CONSTRUCTOR_ACCESS Indicate the init functions access modifier. If value equals to protected, then these functions are protected. If value equals to public, these functions are public
protected by default. */ #ifndef CC_CONSTRUCTOR_ACCESS #define CC_CONSTRUCTOR_ACCESS protected #endif
### 两阶段构造器及静态create()函数用法
* 第一阶段是运行C++类构造器。在C++类的默认构造器中,成员变量须设定为默认值。但我们不应在默认构造器中编写任何逻辑。
* 第二阶段是调用xxx::init()函数
### 用两阶段构造器的原因
* (官方)C++默认构造器不能返回表明我们逻辑正确与否的bool 值, 若使用C++关键词try/catch(捕获/异常)同样会给调用方返回失败状态,但是使用try/catch(捕获/异常)显然将增加你源代码编译后的二进制文件的大小。
### 扩展阅读
* http://cn.cocos2d-x.org/article/index?type=cocos2d-x&url=/doc/cocos-docs-master/manual/framework/native/v3/easy-to-learn-api-style/zh.md
* 设计的两难:选择异常还是两段构造 http://www.cppblog.com/luckycat/archive/2010/03/04/108899.aspx