Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to store 10 Obj object in objList, but i don't know when is appropriate use delete in this case. If i use delete Obj; in the line where i note in below code, will the Obj still be stored in objList?

struct Obj {
    int u;
    int v;
};

vector<Obj> objList;

int main() {
    for(int i = 0; i < 10; i++) {
        Obj *obj = new Obj();
        obj->u = i;
        obj->v = i + 1;
        objList.push_back(*obj);
        // Should i use "delete Obj;" here? 
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
102 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yes, you should.

There should be a corresponding delete for every new in your program.

But your program doesn't need dynamic allocation:

Obj obj;
obj.u = i;
obj.v = i + 1;
objList.push_back(obj);

Also, your syntax was wrong - objList.push_back(*Obj); // should be *obj, not *Obj


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...