与3D动态单元格数组的析构函数出错

时间:2016-05-19 10:49:50

标签: c++ graphics cell destructor dynamic-arrays

我正在处理一个图形项目,我想实现一个3D网格,其中每个单元格都是一个类,所以我可以存储必要的信息。我想使用动态数组,因此,根据此处发现的其他问题,我编写了这段代码:

class Cell {
 public:
    Cell(const Eigen::Vector3i& idx=Eigen::Vector3i::Zero()):
        _idx(idx){
        _parent = 0;
        _distance = std::numeric_limits<int>::max();
    }

    inline bool operator < (const Cell& c){
        for (int i=0; i<3; i++){
            if (_idx[i]<c._idx[i])
                return true;
            if (_idx[i]>c._idx[i])
                return false;
        }
        return false;
    }

    Eigen::Vector3i _idx;
    Cell* _parent;
    float _distance;
};

class DenseGrid {
 public:
    DenseGrid(float resolution_=0,
        const Eigen::Vector3i& size_=Eigen::Vector3i::Zero(),
            const Eigen::Vector3f& origin_=Eigen::Vector3f::Zero()):
                _resolution(resolution_),_size(size_),_origin(origin_) {

        _inverse_resolution = 1./_resolution;
        _num_cells = _size.x()*_size.y()*_size.z();
        _data = new Cell[_num_cells];
        _ptrs = new Cell**[_size.x()];
        for(size_t x=0; x < _size.x(); x++) {
        _ptrs[x] = new Cell*[_size.y()];
        for(size_t y=0; y < _size.y(); y++) {
            _ptrs[x][y] = _data + y*_size.z() + x*_size.y()*_size.z();
        }
        }
    }
    ~DenseGrid() {
        delete [] _data;
        for(size_t x=0; x < _size.x(); x++) {
        for(size_t y=0; y < _size.y(); y++) {
            delete [] _ptrs[x][y];
        }
        delete [] _ptrs[x];
        }
        delete [] _ptrs;
    }

    inline Cell* data(){return _data;}
    inline int numCells(){return _num_cells;}

 protected:
    Eigen::Vector3f _origin;
    float _resolution;
    float _inverse_resolution;
    Eigen::Vector3i _size;
    int _num_cells;
    Cell* _data;
    Cell*** _ptrs;

};

当我尝试将此类与基本示例一起使用时,我收到运行时错误:

  

*`./signed_distance_function'错误:双重免费或损坏(!prev):0x0000000001802010 *

     

中止

我认为是由析构函数引起的。拜托,有人能告诉我哪里出错了吗?

谢谢, 费德里科

修改

这是我测试代码的方式:

#include "three_d_grid.h"

using namespace std;

int main() {
    Eigen::Vector3f orig(0,0,0);
    float res = 0.25;
    Eigen::Vector3i size(3,3,3);
    DenseGrid dg(res,size,orig);

    int n = dg.numCells();
    Cell* data = new Cell[n];

    for(size_t idx=0; idx < n; idx++)
        cout << data[idx]._idx.transpose() << "\t";
    cout << "\n";
    return 0;
}

编辑2

@Anto:我按照你的建议,错误消失了,所以正确的方法是

DenseGrid::~DenseGrid() {
    for(size_t x=0; x < _size.x(); x++) {
        delete [] _ptrs[x];
    }
    delete [] _ptrs;
    delete [] _data;

}

...

0 个答案:

没有答案