不要对含有virtual函数的类使用memset

来源:互联网 发布:异星工厂修改数据 编辑:程序博客网 时间:2024/06/05 02:48
Using Memset On Class Objects

It's common practice in C, to do a memset on structures, in order to initialize all member variables to some default value, usually NULL. Similarly, you can use memset to initialize class objects. But what happens if the class contains some virtual functions?

Let's take an example:
class GraphicsObject{protected:char *m_pcName;int m_iId;//etcpublic:virtual void Draw() {}virtual int Area() {}char* Name() { return m_pcName;}};class Circle: public GraphicsObject{void Draw() { /*draw something*/ }int Area() { /*calculate Area*/ }};void main(){GraphicsObject *obj = new Circle; //Create an objectmemset((void *)obj,NULL,sizeof(Circle)); //memset to 0obj->Name(); //Non virtual function call works fineobj->Draw(); //Crashes here}

This results in a crash, because every object of a class containing virtual functions contains a pointer to the virtual function table(vtbl). This pointer is used to resolve virtual function calls, at run time and for dynamic type casting. The pointer is hidden, and is not accessible to programmers by normal means. When we do a memset, the value of this pointer also gets overwritten, which, in turn, results in a crash, if a virtual function is called.

To avoid such mysterious crashes, memset should not be used on the objects of a class with virtual functions. Instead use the default constructor or an init routine to initialize member variables.
原创粉丝点击