<分区>
我遇到了一个奇怪的问题,我创建了这个简单的程序来演示它。我知道代码本身没有多大意义,但我想强调一些我不理解的地方。
#include <iostream>
using namespace std;
class tempClass{
public:
float n;
tempClass(){};
~tempClass(){} //VERY IMPORTANT LINE
void* operator new[](size_t size);
};
void* tempClass::operator new[](size_t size){
tempClass* a;
a= ::new tempClass[2];
for (int i = 0; i < 2; i++)
{
a[i].n = i*10;
}
cout << a << endl;
return a;
}
int main(){
tempClass* a;
a = new tempClass[2];
cout << a << endl;
cout << a[0].n << endl;
return 0;
}
在代码中,我为我创建的类重载了 operator new。但是,函数的行为会发生变化,这取决于我是否包含类的析构函数。我注意到,如果我不包含析构函数,一切正常,而如果我这样做,指针 a
的返回值将增加 8
在一直。因此,在这个例子中,如果我包含析构函数,程序的最后一个 cout
将打印 20
,如果不包含析构函数,则打印 0
,在一直。为什么会这样?