C++ virtual function table memory cost

前端 未结 13 1771
抹茶落季
抹茶落季 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:44

    If you know all of the derived types and their respective update functions in advance, you could store the derived type in A, and implement manual dispatch for the update method.

    However, as others are pointing out, you are really not paying that much for the vtable, and the tradeoff is code complexity (and depending on alignment, you might not be saving any memory at all!). Also, if any of your data members have a destructor, then you also have to worry about manually dispatching the destructor.

    If you still want to go this route, it might look like this:

    class A;
    void dispatch_update(A &);
    
    class A
    {
    public:
        A(char derived_type)
          : m_derived_type(derived_type)
        {}
        void update()
        {
            dispatch_update(*this);
        }
        friend void dispatch_update(A &);
    private:
        char m_derived_type;
    };
    
    class B : public A
    {
    public:
        B()
          : A('B')
        {}
        void update() { /* stuff goes in here... */ }
    
    private:
        double a, b, c;
    };
    
    void dispatch_update(A &a)
    {
        switch (a.m_derived_type)
        {
        case 'B':
            static_cast (a).update();
            break;
        // ...
        }
    }
    

提交回复
热议问题