Adding pointers to vector in loop

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

提交回复
热议问题