如何处理动态分配的类

How to deallocate the dynamically allocated classes?

本文关键字:动态分配 处理 何处理      更新时间:2023-10-16

我在下面有一个简单的程序:

#include <iostream>            
using namespace std;
class pithikos {
public:
    //constructor
    pithikos(int x, int y){
        xPosition = x;
        yPosition = y;
    }
    //multiplicator of x and y positions
    int xmuly(){
        return xPosition*yPosition;
    }   
private:
    int xPosition;
    int yPosition;
};
int main(void){

//alloccate memory for several number of pithikous
pithikos **pithik = new pithikos*[10];
for (int i = 0; i<10; i++){
     pithik[i] = new pithikos(i,7);
}
cout << pithik[3]->xmuly() << endl; /*simple print statement for one of the pithiks*/
//create pithikos1 
pithikos pithikos1(5,7);
cout << pithikos1.xmuly() << endl;
//delete alloccated memory
for (int i=0; i<10; i++) delete pithik[i];
delete [] pithik;
cout << pithik[4]->xmuly() << endl;
}

课程只需乘以两个数字并乘以它们并返回值。但是我希望抹灰生长和死亡。

所以我在此示例中分配了10个对象(Pithikos),然后我正在测试天气。

当我运行程序时,我会得到这个:

21

35

28

我的问题是:为什么在使用命令后获得值28?

delete [] pithik;

如果不这样做,我如何删除对象?

始终使用new关键字删除您创建的内容。如果使用new关键字创建一系列指针,请使用delete[]删除数组的所有指针元素。

如果不这样做,我如何删除对象?

这是删除使用new关键字创建的对象的正确方法。

使用命令后为什么要获得值28?

删除指针后,您不应尊重指针。它导致不确定的行为。您可能会得到旧值或讨厌的分割故障。

1个呼叫删除将标记为免费的内存区域。它不必重置其旧值。

2-访问释放记忆肯定会导致您的行为不确定,因此尝试

是极其不可理解的事情