I load a text file then from its data I create dynamically allocated objects then store their pointers in a vector and depending on each object type store it in one of another two containers, I have two questions: first: if I declare and initialize the object inside the read file function then added the pointer to the vector, will this object be available outside the function until I delete it or not? if no what is the solution? second: I use thie following function to free the memory:
for (int it = 0; it < phongItems.size(); it++) {
delete phongItems[it];
phongItems[it] = nullptr;
}
so I delete the objects from the main container which contains all objects, must I do that for the other containers which have the same pointers or not?
note: I am not very strong in that point so if there is a misunderstand please clear it and hope less down votes.
Edit:
I load the text file using the following method, I iterate its lines then each line should create an item which have to be added to a vector to use later:
void Game::loadLevel(std::string file) {
initAssets(mgr, dataPath, file);
std::string line;
ifstream f(dataPath + file);
if (!f.is_open())
LOGE("game error while opening file %s", file.c_str());
while (getline(f, line)) {
std::vector<std::string> tokens;
sSplit(line, ' ', tokens);
if (tokens[0] == "MESH") {
std::vector<std::string> typeToken;
sSplit(tokens[2], '=', typeToken);
std::vector<std::string> nameToken;
sSplit(tokens[1], '=', nameToken);
std::vector<std::string> countToken;
sSplit(tokens[3], '=', countToken);
std::vector<std::string> matrixToken;
sSplit(tokens[4], '=', matrixToken);
int count = atoi(countToken[1].c_str());
//if I declare the pointer here and added it to the vector I can't use it later
StaticItem* item;
std::vector<GLfloat> mToken;
fSplit(matrixToken[1], ',', mToken);
item = new StaticItem(*engine, "/models/" + nameToken[1] + ".obj",nullptr,0);
item->narrow = true;
engine->addItem(item, true, true);
}
}
if (f.bad())
LOGE("game error while reading file %s", file.c_str());
f.close();
}
void Engine::addItem(EngineItem* item, bool collision, bool loader) {
if (collision)
collisionItems.push_back(item);
if (loader)
loadItems.push_back(item);
phongItems.push_back(item);
}
if I use smart pointers or raw pointers the pointer will be out of scope after the function finishes, so which is the idea?