C++ virtual function table memory cost

前端 未结 13 1781
抹茶落季
抹茶落季 2020-12-03 08:14

Consider:

class A
{
    public:
        virtual void update() = 0;
}

class B : public A
{
    public:
        void update() { /* stuff goes in here... */ }
         


        
13条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 08:41

    If you really want to save memory of virtual table pointer in each object then you can implement code in C-style...

    E.g.

    struct Point2D {
    int x,y;
    };
    
    struct Point3D {
    int x,y,z;
    };
    
    void Draw2D(void *pThis)
    {
      Point2D *p = (Point2D *) pThis;
      //do something 
    }
    
    void Draw3D(void *pThis)
    {
      Point3D *p = (Point3D *) pThis;
     //do something 
    }
    
    int main()
    {
    
        typedef void (*pDrawFunct[2])(void *);
    
         pDrawFunct p;
         Point2D pt2D;
         Point3D pt3D;   
    
         p[0] = &Draw2D;
         p[1] = &Draw3D;    
    
         p[0](&pt2D); //it will call Draw2D function
         p[1](&pt3D); //it will call Draw3D function
         return 0; 
    }
    

提交回复
热议问题