在循环中添加指向矢量的指针 [英] Adding pointers to vector in loop

查看:51
本文介绍了在循环中添加指向矢量的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下代码有些困惑

void foo() {

  std::list<A*> list;

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

  for (Iterator it = list.begin(); it != list.end(); it++) {
     std::cout <<  (*it);
  }
}

会打印出具有构造函数参数2的对象a的三倍,即循环中构造的最后一个对象.

which prints out three times the object a with constructor argument 2, i.e. the last object constructed in the loop.

我在做什么错了?

推荐答案

您有一个悬空指针列表.

You have a list of dangling pointers.

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

在每次迭代中,此循环都会创建一个 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.

这篇关于在循环中添加指向矢量的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆