C++虚函数表内存开销

C++ virtual function table memory cost(C++虚函数表内存开销)
本文介绍了C++虚函数表内存开销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

考虑:

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++虚函数表内存开销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)