C++ virtual function table memory cost

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

    How many instances of A-derived classes do you expect? How many distinct A-derived classes do you expect?

    Note that even with a million of instances, we are talking about a total of 32MB. Up to 10 millions, don't sweat it.

    Generally you need an extra pointer per instance, (if you are running on an 32 bit platform, the last 4 byte are due to alignment). Each class consumes additional (Number of virtual functions * sizeof(virtual function pointer) + fixed size) bytes for its VMT.

    Note that, considering alignment for the doubles, even a single byte as type identifier will bring up the array element size to 32. So Stjepan Rajko's solution is helpful in some cases, but not in yours.

    Also, don't forget the overhead of a general heap for so many small objects. You may have another 8 bytes per object. With a custom heap manager - such as an object/size specific pool allocator - you can save more here and employ a standard solution.

提交回复
热议问题