C++ virtual function table memory cost

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

    Typically, every instance of a class with at least one virtual function will have an extra pointer stored with its explicit data members.

    There's no way round this, but remember that (again typically) each virtual function table is shared between all instances of the class, so there is no great overhead to having multiple virtual functions or extra levels of inheritance once you've paid the "vptr tax" (small cost of vtable pointer).

    For larger classes the overhead becomes much smaller as a percentage.

    If you want functionality that does something like what virtual functions do, you are going to have to pay for it in some way. Actually using native virtual functions may well be the cheapest option.

提交回复
热议问题