c++ - Dangling Sprite pointer member variable after Sprite::create() -
i getting started cocos2d-x , encountering problem. below code throws read access violation error @ s->getchildrencount();
.
helloworldscene.h
class helloworld : public cocos2d::layer { public: static cocos2d::scene* createscene(); virtual bool init(); void update(float) override; create_func(helloworld); private: cocos2d::sprite* s; };
helloworldscene.cpp
scene* helloworld::createscene() { auto scene = scene::create(); auto layer = helloworld::create(); scene->addchild(layer); return scene; } bool helloworld::init() { if ( !layer::init() ) { return false; } s = sprite::create(); this->scheduleupdate(); return true; } void helloworld::update(float delta) { int k = s->getchildrencount(); ... }
my guess s
becomes dangling pointer , has reference counting. read how reference counting works did not understand it.
how possible sprite gets destroyed @ end of init
? doing it?
what proper way solve issue? s->retain()
after sprite::create()
, add helloworldscene
destructor s->release()
? if this, don't see benefit on using traditional c++ new
, delete
.
first off, there's no dangling pointer, pointer created no longer exists , s
nullptr
. why access violation error when try access getchildrencount()
method.
objects created using create()
methods evaluated released method they're created in ends. means if object has no references , not marked retained, created object deconstructed. if want behaviour change have call retain, , release respectively, concluded.
one of benefits of s->retain()
, s->release()
, or reference counting in general, versus using new
, delete
don't have worry data membership outside class ie. when call delete, sure resource not used anywhere longer? question becomes unnecessary using reference counting , retain/release mechanism.
Comments
Post a Comment