Delete pointer to multidimensional array in class through another pointer - how?

前端 未结 4 2098
眼角桃花
眼角桃花 2020-12-04 03:18

I have a pointer to a class, that have a pointer to a multidimensional array but I can\'t seem to delete it from memory when I need to or set it to NULL.

#de         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-04 03:56

    If you want a 2D array of pointers to , create a class to handle that, then put an instance of it in your TestClass. As far as how to do that, I'd generally use something on this order:

    template 
    class matrix2d {
        std::vector data;
        size_t cols;
        size_t rows;
    public:
        matrix2d(size_t y, size_t x) : cols(x), rows(y), data(x*y) {}
        T &operator()(size_t y, size_t x) { 
            assert(x<=cols);
            assert(y<=rows);
            return data[y*cols+x];
        }
        T operator()(size_t y, size_t x) const { 
            assert(x<=cols);
            assert(y<=rows);
            return data[y*cols+x];
        }
    };
    
    class TestClass { 
        matrix2d array(10, 10);
    public:
        // ...
    };
    

    Given that you're storing pointers, however, you might want to consider using Boost ptr_vector instead of std::vector.

提交回复
热议问题