小编Ijl*_*lal的帖子

重新初始化指针是不好的做法吗?

我有一个Image类,最初我不知道图像的尺寸,所以我只是将data_指针初始化为一个大小为0的数组.后来当我找到图像信息时,我重新初始化data_为一个新的大小.这会在内存中造成任何问题吗?有没有更清洁的方法来做到这一点?

以下是我写的课程:

class Image
{
private:
    int numRows_, numCols_;
    unsigned char* data_;
public:
    Image() : numRows_(0), numCols_(0), data_(new unsigned char[0])
    {}
    void setData(int r, int c, unsigned char* data)
    {
        this->numRows_ = r;
        this->numCols_ = c;
        this->data_ = new unsigned char[r*c];
        for (int i = 0; i < r*c; i++)
        {
            this->data_[i] = data[i];
        }
    }
    int rows();
    int cols();
    unsigned char* data();
    ~Image();
};
Run Code Online (Sandbox Code Playgroud)

提前致谢

c++

3
推荐指数
1
解决办法
366
查看次数

标签 统计

c++ ×1