C ++虚函数表内存成本 [英] C++ virtual function table memory cost

查看:97
本文介绍了C ++虚函数表内存成本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑:

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

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

    private:
        double a, b, c;
}

class C { 
  // Same kind of thing as B, but with different update function/data members
}

我现在在做:

A * array = new A[1000];
array[0] = new B();
array[1] = new C();
//etc., etc.

如果我调用 sizeof (B),返回的大小是3个双成员所需的大小,加上虚函数指针表所需的一些开销。现在,回到我的代码,结果是'sizeof(myclass)'是32;也就是说,我使用24字节用于我的数据成员,8字节用于虚拟函数表(4个虚拟函数)。我的问题是:有什么办法,我可以精简这个吗?我的程序最终会使用大量的内存,我不喜欢25%的声音被虚拟函数指针吃掉。

If i call sizeof(B), the size returned is the size required by the 3 double members, plus some overhead required for the virtual function pointer table. Now, back to my code, it turns out that 'sizeof(myclass)' is 32; that is, I am using 24 bytes for my data members, and 8 bytes for the virtual function table (4 virtual functions). My question is: is there any way I can streamline this? My program will eventually use a heck of a lot of memory, and I don't like the sound of 25% of it being eaten by virtual functions pointers.

推荐答案

v表是每个类,而不是每个对象。每个对象只包含到其v表的指针。所以每个实例的开销是 sizeof(pointer)(通常是4或8个字节)。对于类对象的sizeof有多少个虚拟函数无关紧要。考虑到这一点,我想你不应该太担心。

The v-table is per class and not per object. Each object contains just a pointer to its v-table. So the overhead per instance is sizeof(pointer) (usually 4 or 8 bytes). It doesn't matter how many virtual functions you have for the sizeof the class object. Considering this, I think you shouldn't worry too much about it.

这篇关于C ++虚函数表内存成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆