Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

c++ - When to use "delete"?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...