Adding pointers to vector in loop

前端 未结 3 748
迷失自我
迷失自我 2021-01-16 21:48

I am slightly confused about the following code

void foo() {

  std::list list;

  for (int i = 0; i < 3; i ++) {
    A a = A(i);
    list.push_         


        
3条回答
  •  误落风尘
    2021-01-16 22:10

    If you'd like to worry less about remembering to de-allocate the allocated memory (and have a nicer less error prone code) you should use unique_ptr or shared_ptr (read about them and shoose whichever fits your needs best).

    Here is a small example (notice how the elements in the vector get deleted when the vector goes out of scope):

    cout<<"Scope begins"< > v;
        for (int i=0; i<5; ++i){
            v.push_back(unique_ptr(new A(i)) );
        }
    }
    cout<<"Scope ends"<

    Live demo here.

提交回复
热议问题