为什么这段代码会崩溃?
class Point {
public:
double x;
double y;
};
class Edge {
public:
Point org;
Point dst;
Edge(const Point& org, const Point& dest) {
this->org = org;
this->dst = dest;
}
};
class Box {
private:
std::vector<std::shared_ptr<Edge>> _edges;
void _init(const Point& lb, const Point& rt) {
std::cout << "Initialize Box ... " << std::endl;
// CRASH SOMEWHERE HERE ...
this->_edges.reserve(4);
this->_edges[0] = std::make_shared<Edge>(lb.x, lb.y, rt.x, lb.y);
this->_edges[1] = std::make_shared<Edge>(rt.x, lb.y, rt.x, rt.y);
this->_edges[2] = std::make_shared<Edge>(rt.x, rt.y, lb.x, rt.y);
this->_edges[3] = std::make_shared<Edge>(lb.x, rt.y, lb.x, lb.y);
std::cout << "Box object initialized" << std::endl;
}
public:
Box(const Point& lb, const Point& rt) {
this->_init(lb, rt);
}
};
答案 0 :(得分:3)
reserve
为向量元素保留空间,但不向向量添加任何可访问的元素。大小仍为零,因此您对_edges[0]
等的访问超出范围。
相反,使用resize
调整向量大小,使用现有代码重新分配元素:
this->_edges.resize(4);
this->_edges[0] = std::make_shared<Edge>(lb.x, lb.y, rt.x, lb.y);
// and so on
或使用push_back
添加元素:
this->_edges.reserve(4);
this->_edges.push_back(std::make_shared<Edge>(lb.x, lb.y, rt.x, lb.y));
// and so on
或从初始化列表中分配
this->_edges = {
std::make_shared<Edge>(lb.x, lb.y, rt.x, lb.y),
// and so on
};
或简化代码以在初始化列表中初始化它,这些东西属于
Box(const Point& lb, const Point& rt) :
_edges {
std::make_shared<Edge>(lb.x, lb.y, rt.x, lb.y),
// and so on
}
{}
答案 1 :(得分:1)
vector::reserve
保留空间,但实际上并没有调整数组的大小。请尝试使用resize
。