我有一个图像类,最初我不知道图像尺寸,所以我只是初始化一个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();
};
在此先感谢
任何理由不只是将其设置为'nullptr'? – Rotem
很高兴看到您的析构函数实现... –
您不能重新初始化东西。初始化只进行一次。你之后做的任何事情只是任务。 –