Adding pointers to vector in loop

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

提交回复
热议问题