C++ delete pointer to dynamic allocated object

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?

Upvotes: 1

Views: 682

Answers (1)

Jeka
Jeka

Reputation: 1384

To many question in one, but I will try to explain.

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?

Yes, it will be available from the mentioned vector, if object was created on the heap (with new).

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?

Deleting or dereferencing (using) already deleted pointer is an error, you should only remove pointer from vector, to prevent it further usage.

if I use smart pointers or raw pointers the pointer will be out of scope after the function finishes, so which is the idea?

If you will use smart pointers it depends. Storing non-smart pointers in vector is useless because object will be deleted as you pointed. So you should put shared pointer in vector, in this case object will not be deleted untill any shared pointer exist.

To summarize I bet that using shared pointers is the best solution. Crate shared pointer, put it in any vectors you need. When you want to delete object, just remove shared from any vectors and object will be automatically deleted.

Upvotes: 2

Related Questions