0
在類MainLayer的init()函數中,我使用一個靜態向量來存儲擴展Node的類塊的指針。然後,5秒後(我使用一個計劃來觸發運行runBlock()函數),我嘗試獲取存儲在靜態向量中的數據。cocos2dx 3.10中的內存管理是什麼?
但是,我得到的數據是錯誤的。從調試中,我明白這是內存錯誤。我初始化的數據看起來像被刪除。
我不知道爲什麼數據被刪除。請幫助我,謝謝!
這裏是我的關鍵代碼:
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
}
不要忘記釋放後使用 – Striker
'的cocos2d :: VECTOR'。它會自動保留和釋放元素。 – Zen