【发布时间】:2019-10-17 08:13:05
【问题描述】:
#include <iostream>
#include <vector>
//#include <string>
struct Point {
Point(int _x, int _y) {
x = _x;
y = _y;
}
int x;
int y;
Point *parent;
};
int main() {
Point start(3, 4);
std::vector<Point> points;
points.push_back(start);
std::cout << points.back().x << "," << points.back().y << "\n";
Point one(4, 5);
one.parent = &points.at(0);
//std::cout << "testing: " << one.parent->x << "," << one.parent->y << "\n";
points.push_back(one);
std::cout << "One: " << points[1].x << "," << points[1].y << "\n";
std::cout << "One's parents: " << points[1].parent->x << "," << points[1].parent->y << "\n";
Point two(10, 3);
two.parent = &points.back();
points.push_back(two);
std::cout << "Two: " << points[2].x << "," << points[2].y << "\n";
std::cout << "Two's parent: " << points[2].parent->x << "," << points[2].parent->y << "\n";
Point three(12, 7);
three.parent = &points[1];
points.push_back(three);
std::cout << "Three: " << points[3].x << "," << points[3].y << "\n";
std::cout << "Three's parents: " << points[3].parent->x << "," << points[3].parent->y << "\n";
return 1;
}
我得到以下结果: 3,4 一:4,5 父母:0,0 二:10,3 两人的父母:4,5 三:12,7 三人的父母:4,5
即使我将一个父点指向向量的第一个元素,该值最终还是 0,0。但是,其他指针指向我想要的元素。
【问题讨论】:
-
一旦你这样做了
points.push_back(one);std::vector被允许重新分配保存所有数据的整个数组,所以这意味着如果你之前存储了指针,例如:&points.back(),它可能不再是有效。 -
注意:如果您需要扩展代码,可以扩展此问题的更安全的解决方案是将
vector设为std::vector<std::shared_ptr<Point>>,并让parent成为Point的成员也是std::shared_ptr<Point>(假设它是DAG;如果它可以有循环,则需要std::weak_ptr<Point>,并且管理变得更加困难)。这避免了Points 和存储它们的vector之间的紧密耦合(其中parent仅在有效的全局vector的上下文中才有意义)。 -
明智地使用
std::make_shared(这既更安全,又允许直接std::shared_ptr无法做到的性能优化),它不会增加太多开销,而且可以让你解放相当多。
标签: c++ c++11 pointers stdvector