0

我可以释放用于分配对象的内存吗?如果是这样,我该怎么做?

class CRectangle {
    int width, height;
public:
    CRectangle (int,int);
    ~CRectangle ();
    int area () {
        return (width * height);
    }
};

CRectangle::CRectangle (int a, int b) {
    width = a;
    height = b;
}

CRectangle::~CRectangle () {
    // Do something here
}

如果我使用动态内存分配,它将是:

   class CRectangle {
        int *width, *height;
    public:
        CRectangle (int,int);
        ~CRectangle ();
        int area () {
            return (*width * *height);
        }
    };

    CRectangle::CRectangle (int a, int b) {
        width = new int;
        height = new int;
        *width = a;
        *height = b;

    }

    CRectangle::~CRectangle () {
        delete width
        delete height
    }

它们确实有相同的输出,那么使用动态内存分配有什么好处呢?

4

3 回答 3

2

要回答这个问题,不。您的所有成员都是在对象实例化时自动分配的。唯一需要担心释放内存的情况是动态分配(因为在超出范围之前无法释放自动内存)。以这两个整数为例:

int a; //automatic allocation at point of declaration, will exist until it falls out of scope
int *a = new int; //dynamic allocation, exists until deleted. Falling out of scope without releasing memory can cause a memory leak

现在,如果您要动态分配对象,那么您可以释放内存,但这是在您的类之外完成的。

CRectangle *rect;
rect = new CRectangle; //dynamically allocated

//....

delete rect; //free memory allocated by rect
于 2013-05-16T05:14:53.070 回答
1

在您的特定示例中,两者在技术上都是正确的,并且在析构函数中不需要做更多的事情。

在第二个示例中,绝对没有任何好处,实际上是在浪费内存,因为在分配内存时存在开销。int最小的此类开销是 12 字节 + 分配本身 - 在您的情况下,如果我们假设为 4 字节(这很常见,但还有其他选择),那么这总共是 16 字节。

当对象大小不同时分配对象是有益的(你的大小总是 one int)[并且最大大小大于分配内存本身的预期开销]或对象是可选的[并且大于预期开销分配对象]。

例如,想象一下,我们让您为每个大小单位CRectangle持有一个CCell对象(例如,它可能是某种游戏中每个单元格的内容)。现在,如果我们还想象一个矩形的每边可以是从 1 x 1 到几千的任意大小,我们不会想要在每个维度上做一个静态二维数组,对吗?所以我们必须动态分配它。出于讨论的目的,我将分配一个大数组width * height,因为这是我们需要的大小。可以考虑进行 2D 分配,但这会使代码更加复杂。

这就是它的样子:

class CRectangle {
    int width, height;
    CCell* cellArray;
public:
    CRectangle (int,int);
    ~CRectangle ();
    int area () {
        return (width * height);
    }
};

CRectangle::CRectangle (int a, int b) {
    width = a;
    height = b;
    cellArray = new CCell[width * height];
}

CRectangle::~CRectangle () {
    delete [] cellArray;
}
于 2013-05-16T06:23:13.527 回答
0

在你设计的类中,你不需要在析构函数中做任何事情。

还行吧:

CRectangle::~CRectangle () {
}
于 2013-05-16T05:19:33.303 回答