我刚刚用 g++(4.7)检查了一个包含几十个虚拟方法的类的大小,因为我听说指针用于虚拟方法,我认为这将是一个糟糕的实现,因为它的每个实例将占用 80 个字节在我的系统上只有 10 个虚拟方法的类。
让我松了一口气,sizeof(<insert typename here>)
只返回了 8 个字节,即我系统上指针的大小。我认为这意味着它存储了一个指向 vtable 的指针,而不是每个方法,并且我只是误解了人们在说什么(或者也许大多数编译器都很愚蠢)。
然而,在我最终测试这个之前,我一直在努力按照我期望的方式使用虚拟方法作为指针。我注意到地址实际上是一个相对非常小的数字,通常低于 100 并且与其他地址相比相差 8 个字节,所以我认为它是某种数组的索引。然后我开始思考如何自己实现 vtables,并且不会使用指针,因为我的测试结果清楚地表明了这一点。我很惊讶地看到它使用了整个 8 个字节(我通过插入一个 char 字段来验证它是否只是填充,该字段返回 16 个字节和 sizeof)。
相反,我将通过存储一个数组索引(例如 4 个字节,如果使用 65536 个或更少的类和虚拟方法,则甚至为 2 个字节)来实现这一点,该索引将在包含指向 vtables 的指针的查找表中进行搜索,并找到就这样。那么为什么要存储指针呢?出于性能原因,还是他们只是将代码重用于 32 位操作系统(因为它不会影响内存大小)?
先感谢您。
编辑:
有人要求我计算实际节省的内存,我决定做一个代码示例。不幸的是,它变得相当大(他们要求我在两者中都使用 10 个虚拟方法),但我对其进行了测试,它确实有效。它来了:
#include <cstdio>
#include <cstdlib>
/* For the singleton lovers in this community */
class VirtualTableManager
{
unsigned capacity, count;
void*** vtables;
public:
~VirtualTableManager() {
delete vtables;
}
static VirtualTableManager& getInstance() {
static VirtualTableManager instance;
return instance;
}
unsigned addElement(void** vtable) {
if (count == capacity)
{
vtables = (void***) realloc(vtables, (capacity += 0x2000) * sizeof(void**)); /* Reserves an extra 64KiB of pointers */
}
vtables[count] = vtable;
return count++;
}
void** getElement(unsigned index) {
return index < capacity ? vtables[index] : 0; /* Just in case: "Hey guys, let's misuse the API!" */
}
private:
VirtualTableManager() : capacity(0), count(0), vtables(0) { }
VirtualTableManager(const VirtualTableManager&);
void operator =(const VirtualTableManager&);
};
class Real
{
public:
short someField; /* This is required to show the difference, because of padding */
Real() : someField(0) { }
virtual ~Real() {
printf("Real::~Real()\n");
}
virtual void method0() {
printf("Real::method0()\n");
}
virtual void method1(short argument) {
someField = argument;
}
virtual short method2() {
return someField;
}
virtual void method3() { }
virtual void method4() { }
virtual void method5() { }
virtual void method6() { }
virtual void method7() { }
virtual void method8() { }
};
class Fake
{
static void** vtable;
static unsigned classVIndex; /* Don't know what to call it, please forgive me for the lame identifier */
public:
unsigned instanceVIndex;
short someField;
Fake() : instanceVIndex(classVIndex), someField(0) { }
~Fake() {
reinterpret_cast<void (*)(Fake*)>(VirtualTableManager::getInstance().getElement(instanceVIndex)[9])(this);
}
void method0() {
reinterpret_cast<void (*)(Fake*)>(VirtualTableManager::getInstance().getElement(instanceVIndex)[0])(this);
}
void method1(short argument) {
reinterpret_cast<void (*)(Fake*, short argument)>(VirtualTableManager::getInstance().getElement(instanceVIndex)[1])(this, argument);
}
short method2() {
return reinterpret_cast<short (*)(Fake*)>(VirtualTableManager::getInstance().getElement(instanceVIndex)[2])(this);
}
void method3() {
reinterpret_cast<void (*)(Fake*)>(VirtualTableManager::getInstance().getElement(instanceVIndex)[3])(this);
}
void method4() {
reinterpret_cast<void (*)(Fake*)>(VirtualTableManager::getInstance().getElement(instanceVIndex)[4])(this);
}
void method5() {
reinterpret_cast<void (*)(Fake*)>(VirtualTableManager::getInstance().getElement(instanceVIndex)[5])(this);
}
void method6() {
reinterpret_cast<void (*)(Fake*)>(VirtualTableManager::getInstance().getElement(instanceVIndex)[6])(this);
}
void method7() {
reinterpret_cast<void (*)(Fake*)>(VirtualTableManager::getInstance().getElement(instanceVIndex)[7])(this);
}
void method8() {
reinterpret_cast<void (*)(Fake*)>(VirtualTableManager::getInstance().getElement(instanceVIndex)[8])(this);
}
protected:
Fake(unsigned instanceVIndex, short someField)
: instanceVIndex(instanceVIndex), someField(someField) { }
/* The 'this' keyword is an automatically passed pointer, so I'll just manually pass it and identify it as 'self' (thank you, lua, I would have used something like 'vthis', which would be boring and probably incorrect) */
static void vmethod0(Fake* self) {
printf("Fake::vmethod0(%p)\n", self);
}
static void vmethod1(Fake* self, short argument) {
self->someField = argument;
}
static short vmethod2(Fake* self) {
return self->someField;
}
static void vmethod3(Fake* self) { }
static void vmethod4(Fake* self) { }
static void vmethod5(Fake* self) { }
static void vmethod6(Fake* self) { }
static void vmethod7(Fake* self) { }
static void vmethod8(Fake* self) { }
static void vdestructor(Fake* self) {
printf("Fake::vdestructor(%p)\n", self);
}
};
class DerivedFake : public Fake
{
static void** vtable;
static unsigned classVIndex;
public:
DerivedFake() : Fake(classVIndex, 0) { }
~DerivedFake() {
reinterpret_cast<void (*)(DerivedFake*)>(VirtualTableManager::getInstance().getElement(instanceVIndex)[1])(this);
}
void method0() {
reinterpret_cast<void (*)(DerivedFake*)>(VirtualTableManager::getInstance().getElement(instanceVIndex)[0])(this);
}
protected:
DerivedFake(unsigned instanceVIndex, short someField)
: Fake(instanceVIndex, someField) { }
static void vmethod0(DerivedFake* self) {
printf("DerivedFake::vmethod0(%p)\n", self);
}
static void vdestructor(DerivedFake* self) {
printf("DerivedFake::vdestructor(%p)\n", self);
Fake::vdestructor(self); /* call parent destructor */
}
};
/* Make the vtable */
void** Fake::vtable = (void*[]) {
(void*) &Fake::vmethod0, (void*) &Fake::vmethod1,
(void*) &Fake::vmethod2, (void*) &Fake::vmethod3,
(void*) &Fake::vmethod4, (void*) &Fake::vmethod5,
(void*) &Fake::vmethod6, (void*) &Fake::vmethod7,
(void*) &Fake::vmethod8, (void*) &Fake::vdestructor
};
/* Store the vtable and get the look-up index */
unsigned Fake::classVIndex = VirtualTableManager::getInstance().addElement(Fake::vtable);
/* Do the same for derived class */
void** DerivedFake::vtable = (void*[]) {
(void*) &DerivedFake::vmethod0, (void*) &Fake::vmethod1,
(void*) &Fake::vmethod2, (void*) &Fake::vmethod3,
(void*) &Fake::vmethod4, (void*) &Fake::vmethod5,
(void*) &Fake::vmethod6, (void*) &Fake::vmethod7,
(void*) &Fake::vmethod8, (void*) &DerivedFake::vdestructor
};
unsigned DerivedFake::classVIndex = VirtualTableManager::getInstance().addElement(DerivedFake::vtable);
int main_virtual(int argc, char** argv)
{
printf("size of 100 instances of Real including padding is %lu bytes\n"
"size of 100 instances of Fake including padding is %lu bytes\n",
sizeof(Real[100]), sizeof(Fake[100]));
Real *real = new Real;
Fake *fake = new Fake;
Fake *derived = new DerivedFake;
real->method1(123);
fake->method1(456);
derived->method1(789);
printf("real::method2() = %hi\n"
"fake::method2() = %hi\n"
"derived::method2() = %hi\n", real->method2(), fake->method2(), derived->method2());
real->method0();
fake->method0();
derived->method0();
delete real;
delete fake;
delete derived;
return 0;
}
不要害怕,我通常不会将定义放在这样的类中。我只是在这里做了,希望能提高可读性。无论如何,输出:
size of 100 instances of Real including padding is 1600 bytes
size of 100 instances of Fake including padding is 800 bytes
real::method2() = 123
fake::method2() = 456
derived::method2() = 789
Real::method0()
Fake::vmethod0(0x1bd8040)
DerivedFake::vmethod0(0x1bd8060)
Real::~Real()
Fake::vdestructor(0x1bd8040)
DerivedFake::vdestructor(0x1bd8060)
Fake::vdestructor(0x1bd8060)
它可能不是线程安全的,可能包含大量可怕的错误,也可能效率相对较低,但我希望它能够展示我的概念。它在 64 位 Ubuntu 上使用 g++-4.7 进行了测试。我怀疑 32 位系统对大小有任何好处,因为我节省了不到一个字(4 个字节,这么多!)我不得不在其中放置一个字段以显示效果。随意对速度进行基准测试(如果你这样做,请先优化它,我匆忙这样做)或在其他架构/平台和其他编译器上测试效果(我想看看结果,所以如果你这样做,请分享它们)。当有人发现需要创建一个 128/256 位平台,创建一个内存支持非常有限但速度令人难以置信的处理器,或者使用每个实例上的 vtable 使用 21 个字节的编译器时,类似的东西可能很有用。
编辑:
糟糕,代码示例是一个derp。解决它。