【发布时间】:2013-05-21 05:18:46
【问题描述】:
我在整个程序中有一些对象面临类似问题。一个例子:
我有一个 Image 类:
class Image
{
public:
Image();
Image(const Image& copy);
~Image();
void loadimage(string filename);
void saveimage(string filename);
Image superimpose(const Image& ontop, Color mask);
int getwidth();
int getheight();
Image operator=(const Image&);
protected:
Color** pixels;
int width;
int height;
ImageLoader* loader;
};
它有一个拷贝构造函数:
Image::Image(const Image& copy)
{
width = copy.width;
height = copy.height;
loader = copy.loader;
pixels = new Color*[height];
for(int i = 0; i < height; i++)
{
pixels[i] = new Color[width];
}
for(int h = 0; h < height; h++)
{
for(int w = 0; w < width; w++)
{
pixels[h][w] = copy.pixels[h][w];
}
}
}
颜色是一个结构体:
struct Color
{
unsigned int r;
unsigned int g;
unsigned int b;
};
我担心的是我创建了一个 Color 结构的动态二维数组,但我不确定何时何地删除它。我在我的 Image 析构函数中实现了以下内容,但我不能 100% 确定它是否在做这项工作,我不确定如何检查它是否有效:
Image::~Image()
{
for(int i = 0; i < height; i++)
{
delete[] pixels[i];
}
delete[] pixels;
pixels = NULL;
}
我是否正确实现了内存释放?
【问题讨论】:
-
最正确的方法是根本不实现它并使用可以为您管理内存的东西。此外,将即将被销毁的东西设置为
NULL是毫无意义的。 -
@chris 所以....我会用什么?你没有提到。
-
我一般更喜欢封装一维
std::vector的Matrix类。
标签: c++ dynamic memory-management