[英]Is it bad practice to reinitialize a pointer?
I have an Image class and initially I do not know the image dimensions, so I just initialize a data_
pointer to be an array of size 0. Later when I find the image information I reinitialize data_
to a new size. 我有一个Image类,最初我不知道图像的尺寸,所以我只是将
data_
指针初始化为一个大小为0的数组。后来当我找到图像信息时,我将data_
重新初始化为一个新的大小。 Will this create any problem in memory? 这会在内存中造成任何问题吗? and is there a cleaner way to do this?
有没有更清洁的方法来做到这一点?
Below is the class I have written: 以下是我写的课程:
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();
};
Thanks in advance 提前致谢
This will in fact leak memory. 这实际上会泄漏内存。 The call to
new
allocates memory for the array, even if it is empty . 对
new
的调用为数组分配内存, 即使它是空的 。 As soon as you reassign data_
, the previous array is leaked and can no longer be freed. 一旦重新分配
data_
,前一个数组就会泄漏,无法再释放。
You can either make sure you delete[]
any new[]
you allocate, or just don't allocate an empty array and instead set data_
to nullptr
until you have meaningful data to use. 您可以确保
delete[]
您分配的任何new[]
,或者只是不分配空数组,而是将data_
设置为nullptr
直到您有有意义的数据要使用。
An even better idea is don't allow the creation of an object in an invalid state, require the data in the constructor - see RAII : 更好的想法是不允许在无效状态下创建对象,需要构造函数中的数据 - 请参阅RAII :
In RAII, holding a resource is a class invariant, and is tied to object lifetime: resource allocation (or acquisition) is done during object creation (specifically initialization), by the constructor, while resource deallocation (release) is done during object destruction (specifically finalization), by the destructor.
在RAII中,持有资源是类不变的,并且与对象生存期相关联:资源分配(或获取)在对象创建(特别是初始化)期间由构造函数完成,而资源释放(释放)在对象销毁期间完成(具体完成),由析构函数。
If you do decide to keep setData
, then as mentioned in comments, you also must make sure to delete[]
existing data in setData
before reassigning data_
, in case the method is called more than once. 如果您决定保留
setData
,那么如注释中所述,您还必须确保在重新分配data_
之前delete[]
setData
现有数据,以防多次调用该方法。
I think a cleaner way to do so will be using a vector: 我认为更清洁的方法是使用矢量:
std::vector<unsigned char> v; // vector with size 0
v.resize(r*c); // after size is known, just resize
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.