Cocos2d-x AppDelegate数据成员初始化丢失

Cocos2d-x AppDelegate data member initialization lost

本文关键字:初始化 数据成员 AppDelegate Cocos2d-x      更新时间:2023-10-16

考虑以下类声明

class AppDelegate : private cocos2d::Application
{
private:
  int _test;
  // ....
};

我正在将数据成员int _test初始化为

AppDelegate::AppDelegate() : _test(20) { 
  cocos2d::log("Initialzing %p with _test = %d", this, _test);
}

后来,当代码

bool AppDelegate::applicationDidFinishLaunching() {
  cocos2d::log("Checking %p, found _test = %d", this, _test);
  // ....
}

执行,输出为

Initialzing 0x10da4aa20 with _test = 20
// ....
Checking 0x10da4aa20, found _test = 1056964608

这表示_test未初始化。这个问题似乎是cocos2d-x体系结构特有的,因为我无法在沙箱项目中重现这个问题(其中AppDelegate被交换为一个更简单的类)。

我的问题是:为什么这个初始化丢失了?是否有其他方法可以初始化和使用AppDelegate类中的数据成员?

因此,_test数据成员在执行PhysicsMaterial构造函数时发生了更改:

typedef struct CC_DLL PhysicsMaterial
{
    float density;          ///< The density of the object.
    float restitution;      ///< The bounciness of the physics body.
    float friction;         ///< The roughness of the surface of a shape.
    PhysicsMaterial()
    : density(0.0f)
    , restitution(0.0f)
    , friction(0.0f)
    {}
    PhysicsMaterial(float aDensity, float aRestitution, float aFriction)
    : density(aDensity)
    , restitution(aRestitution)
    , friction(aFriction)
    {} // Watch reveals that this was the culprit ...
}PhysicsMaterial;

显然,这个构造函数中没有任何代码应该更改_test成员的值,这表明早期的构建有问题。

一次彻底的重建和随后的全面重建解决了这个问题。