如何在向量中存储指向静态分配对象的指针?

gsi*_*011 0 c++ pointers reference

让我们说我想制作一个对象向量和另一个指向这些对象的指针向量(我不能使用动态内存).我将这样做的方式是在下面的例子中.

#include <iostream>
#include <vector>

using namespace std;

class Foo {
public:
  int bar;
  Foo(int x) : bar(x) {
  }
};

int main () {
  vector<Foo> foos;
  vector<Foo*> pFoos;
  for (int i = 0; i < 10; i++) {
    Foo foo(i);
    foos.push_back(foo);
    pFoos.push_back(&foos.back());
  }

  for (int i = 0; i < 10; i++) {
    cout << foos[i].bar << endl;
    cout << pFoos[i]->bar << endl;
  }
}
Run Code Online (Sandbox Code Playgroud)

我认为这应该工作,因为foos存储对象的副本,然后我存储对副本的引用(因为原始foo将是未定义的,所以我不应该存储对它的引用).但这就是我得到的:

0
36741184
1
0
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
Run Code Online (Sandbox Code Playgroud)

数字的第一个pFoos是错误的.此外,每次都会有大量的变化.我没有看到任何会导致这种未定义行为的东西.有人能告诉我我做错了什么吗?

myt*_*gel 8

向向量添加项会使以前的所有迭代器无效.如果向量需要重新分配其内部存储,则在向量上调用push_back可能会使得从它获得的指针先前无效.

如果你知道你再也不会再增长向量那么这将有效:

for (int i = 0; i < 10; i++) {
  foos.push_back(Foo(i));
}

for (int i = 0; i < 10; i++) {
  pFoos.push_back(&foos[i]);
}
Run Code Online (Sandbox Code Playgroud)

或者作为罗德里戈的评论:

foos.reserve(10)

for (int i = 0; i < 10; i++) {
  Foo foo(i);
  foos.push_back(foo);
  pFoos.push_back(&foos.back());
}

for (int i = 0; i < 10; i++) {
  cout << foos[i].bar << endl;
  cout << pFoos[i]->bar << endl;
}
Run Code Online (Sandbox Code Playgroud)

  • 并非每个`push_back`都会导致重新分配.仅在分配的空间耗尽时. (2认同)