Adding pointers to vector in loop

前端 未结 3 712
迷失自我
迷失自我 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

    The variable a is local to the first for loop, so it is destroyed at the end of each iteration of the loop. This means that after the loop finishes, all three pointers in list point to objects that no longer exist. Dereferencing those pointers causes undefined behaviour.

    0 讨论(0)
  • 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"<<endl;
    {
        vector< unique_ptr<A> > v;
        for (int i=0; i<5; ++i){
            v.push_back(unique_ptr<A>(new A(i)) );
        }
    }
    cout<<"Scope ends"<<endl;
    

    Live demo here.

    0 讨论(0)
  • 2021-01-16 22:30

    You have a list of dangling pointers.

     for (int i = 0; i < 3; i ++) {
        A a = A(i);
        list(&a);
      }
    

    In each iteration, this loop creates an object of type A, which is immediately destroyed when the iteration completes. So the contents of the list are undefined. You would need something like this:

     for (int i = 0; i < 3; i ++) {
        A* a = new A(i);
        list(a);
      }
    

    ...but don't forget to delete them all in another loop when you're done with the list.

    0 讨论(0)
提交回复
热议问题