【问题标题】:C++ std::shared_ptr and vector crashC++ std::shared_ptr 和向量崩溃
【发布时间】:2014-09-08 16:42:57
【问题描述】:

为什么这段代码会崩溃?

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

【问题讨论】:

  • 我建议在this-&gt;_edges[0] = std::make_shared&lt;Edge&gt;(lb.x, lb.y, rt.x, lb.y); 崩溃和错误段错误。

标签: c++ c++11 vector shared-ptr


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    vector::reserve 保留空间但实际上并没有调整数组的大小。尝试改用resize

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多