通常在C的编程中,我们经常使用memset函数将一块连续的内存区域清零或设置为其它指定的值,最近在移植一段java代码到C++的时候,不当使用memset函数花费了我几个小时的调试时间。对于虚函数的底层机制很多资料都有较详细阐述,但对我个人而言,这次的调试让我感触颇深。
先来看一段代码,在继承的类Advance之中,有很多属性字段,我希望将其清成0或NULL,于是在构造函数中我通过memset将当前类的所有属性置0。
class Base{
public:
virtual void kickoff() = 0;
};
class Advance:public Base{
public:
Advance(){
memset(this, 0, sizeof(Advance));
}
void kickoff(){
count++;
//... do something else;
}
private:
int attr1, attr2;
char* label;
int count;
//...
other attributes, they should be initiated to 0 or NULL at beginning.
};
int _tmain(int argc, _TCHAR* argv[])
{
Base* ptr = new Advance();
ptr->kickoff();