I have been asked in a discussion what are disadavntages of adding virtual function in a C++ class. I said that one disadvantage is that an object of the class has a pointer to its virtual table and for a small C++ class it add 8 bytes to its size on 64-bit platform. If one creates millions of instances of such class that increase memory consumption of a program.
OK, but why actually in C++ there is no such a thing as a tiny pointer to a virtual table or small pointer to a virtual table or compact pointer to a virtual table. Some thing like this:
class [[compact]] base {
~base(){}
virtual f() = 0;
};
class [[tiny]] another_base {
~base(){}
virtual g() = 0;
};
class [[small]] yet_another_base {
~base(){}
virtual h() = 0;
};
class child : public base {
virtual f();
};
class user_type : public another_base {
~base(){}
virtual g();
};
Imagine that I am going to create lots of instances of user_type
(in fact I once had this situation with a real program). By default a compiler creates an instance of user_type
with size of 8 (on 64-bit). But with [[tiny]] attribute only it might be only 1 byte and with [[compact]] only 4 bytes.
Is this feature already available or not? If not it seems to me it is possible to implement it. Like having in a program hidden tiny_vptr
and compact_vptr
and just add first byte or first four bytes to them when it is necessary to find a real pointer to vtable. So in a program it is allowed to have only 256 [[tiny classes]] for example or 65000 [[small]] classses. It is like a choice betweeen maximum speed and saving some memory.
Aucun commentaire:
Enregistrer un commentaire