[英]C++ std::shared_ptr and vector crash
為什么此代碼崩潰?
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);
}
};
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
}
{}
vector::reserve
保留空間,但實際上並不調整數組的大小。 嘗試改用resize
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.