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

查看:42
本文介绍了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个double成员所需的大小,加上虚函数指针表所需的一些开销.现在,回到我的代码,结果是 'sizeof(myclass)' 是 32;也就是说,我为我的数据成员使用了 24 个字节,为虚函数表(4 个虚函数)使用了 8 个字节.我的问题是:有什么办法可以简化这个吗?我的程序最终会使用大量内存,而且我不喜欢虚拟函数指针占用 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-table 的指针.所以每个实例的开销是 sizeof(pointer)(通常是 4 或 8 个字节).对于类对象的大小,您拥有多少个虚函数并不重要.考虑到这一点,我认为您不必太担心.

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天全站免登陆