问题
In class MainLayer init() function, I use a static vector to store the pointer of class block which extend Node. And then, after 5 seconds (I use a schedule to trigger run the function of runBlock()), I try to get data which are stored in static vector.
However, the data that I got was wrong. From the debug, I understand it is the memory error. the data which I initialize looks like be deleted.
I don't konw why the data was deleted. Please help me, Thanks!
Here is my key code:
MainLayer.cpp
std::vector<block*> MainLayer::block_array = std::vector<block*>();
bool MainLayer::init(){
Layer::init();
...
//the schedule
schedule(schedule_selector(MainLayer::runBlock), 5.0f, CC_REPEAT_FOREVER, 0.0f);
//initialization the data
block* b1 = block1::create();
block* b2 = block2::create();
block* b3 = block3::create();
block_array.push_back(b1);
block_array.push_back(b2);
block_array.push_back(b3);
this->addChild(b1->node);
this->addChild(b2->node);
this->addChild(b3->node);
return true;
}
void MainLayer::runBlock(float dt){
Size size = Director::getInstance()->getVisibleSize();
int len = block_array.size();
int rand = floor(CCRANDOM_0_1()*len);
if (rand == len){
rand -= 1;
}
//here is the problem, the memory which "bb" point is not be allocated
//by the way, the value of bb equals b1 when initialize the data (I mean the memory address is equal, but the data in memory is different)
block* bb = block_array[0];
bb->come(); //this is function in class block
}
回答1:
I'm foolish !!!
Although b1->node is added Layer, b1 is not added. So in the next frame, b1 will be recycled.
JUST in MainLayer::init() add code
b1->retain();
b2->retain();
b3->retain();
everything will be normal
来源:https://stackoverflow.com/questions/37066542/what-is-the-memory-management-in-cocos2dx-3-10