如何处理动态分配的类
How to deallocate the dynamically allocated classes?
我在下面有一个简单的程序:
#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-访问释放记忆肯定会导致您的行为不确定,因此尝试
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 在c++中使用动态分配的问题
- 使用递归模板动态分配的多维数组
- 对具有动态分配的内存和析构函数的类对象的引用
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 访问动态分配列表中的元素
- 为什么 std::equal_to会导致动态分配?
- 调用析构函数以释放动态分配的内存
- 动态分配Q_Property变量
- 在 C++ 中搜索动态分配的数组中的出现次数
- 动态分配的聊天数组打印缺失的数据和空
- 处理另一个类中类动态分配的对象数组
- 从函数安全返回和处理动态分配的内存,C++ 11
- 如何处理动态分配的类
- 实现对象列表时,如何处理动态分配
- 如何在C++中正确处理动态分配的多维数组
- 处理容器类中动态分配的内存
- 具有动态分配内存的类的内存处理
- 处理包含动态分配成员的对象向量