【发布时间】:2019-02-14 21:09:49
【问题描述】:
我在下面有这个简单的程序:
#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;
如果不是这样,我该如何删除对象?
【问题讨论】:
-
delete确实删除了对象,之后不允许取消引用指针 -
顺便说一句,您的程序一点也不简单。使用
std::vector很简单,使用pithikos **很复杂、容易出错并且很危险 -
这里是一个不同的链接,描述了类似的未定义行为情况(您可以访问您认为不应访问的内存):stackoverflow.com/a/6445794/487892
-
当我看到一个新的 C++ 程序员期望在使用
delete时内存会消失得无影无踪时,这对我来说总是很幽默。
标签: c++ memory-management dynamic-memory-allocation