gpt4 book ai didi

c++ - 如何在 vector 中存储指向静态分配对象的指针?

转载 作者:太空宇宙 更新时间:2023-11-04 14:45:16 25 4
gpt4 key购买 nike

假设我想创建一个对象 vector 和另一个指向这些对象的指针 vector (我不能使用动态内存)。我将在以下示例中执行此操作。

#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;
}
}

我认为这应该可行,因为 foos 存储了对象的拷贝,然后我存储了对该拷贝的引用(因为原始的 foo 将是未定义的,所以我不应该存储对此的引用)。但这就是我得到的:

0
36741184
1
0
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9

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

最佳答案

将项目添加到 vector 会使所有先前的迭代器失效。如果 vector 需要重新分配其内部存储,则对 vector 调用 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]);
}

或如 rodrigo 所评论:

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;
}

关于c++ - 如何在 vector 中存储指向静态分配对象的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13352047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com