1

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?

  • 2
    You should call `delete` only once by `new`. And using smart pointers or appropriate container should allow to avoid to use any `new` yourself (so no `delete`). – Jarod42 Nov 27 '17 at 10:42
  • @Jarod42 I was using `shared_ptr` before when I was declare them as class members, now I have to create the objects from a text file so I don't know what it contains until I read it, if I declare the `shared_ptr` inside the load function and add it to the container I guess it become out of scope with function ends and become unavailable and I get errors – Mohamed Mousa El-Kheshen Nov 27 '17 at 10:46
  • 1
    You can transfer ownership from your load function. (Without code, hard to give you the correction for your errors). – Jarod42 Nov 27 '17 at 11:05
  • 1. The objects will be available as long as they are not deleted or become out of scope. 2. As @Jarod42 pointed out, delete should be performed only once. – kishore Nov 27 '17 at 11:24
  • @Jarod42 I added the code – Mohamed Mousa El-Kheshen Nov 27 '17 at 11:28
  • "if I declare the shared_ptr inside the load function and add it to the container I guess it become out of scope with function ends and become unavailable and I get errors" This is not quite true. You probably should learn how to use smart pointers. Guessing how they work is not the way to go. – n. m. could be an AI Nov 27 '17 at 12:05

1 Answers1

2

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.

Jeka
  • 1,364
  • 17
  • 33