C++ virtual function table memory cost

前端 未结 13 1780
抹茶落季
抹茶落季 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 09:05

    You're adding a single pointer to a vtable to each object - if you add several new virtual functions the size of each object will not increase. Note that even if you're on a 32-bit platform where pointers are 4 bytes, you're seeing the size of the object increase by 8 probably due to the overall alignment requirements of the structure (ie., you're getting 4 bytes of padding).

    So even if you made the class non-virtual, adding a single char member would likely add a full 8 bytes to the size of each object.

    I think that the only ways you'll be able to reduce the size of you objects would be to:

    • make them non-virtual (you you really need polymorphic behavior?)
    • use floats instead of double for one or more data members if you don't need the precision
    • if you're likely to see many objects with the same values for the data members, you might be able to save on memory space in exchange for some complexity in managing the objects by using the Flyweight design pattern

提交回复
热议问题