-1

I've got the problem that I need to know the size of the biggest derived class of a base class. At the moment I'm using the -D option of the compiler to specify the size, this is the easiest option I could think of, but you always have to update the size manually.

Since this would be nearly impossible to do in c++ itself, I thought maybe could get the information from a language server and then generate a header that contains the information.

Note that I have no experience in this, but the language server should have all the information that I need right?

How difficult would it be to implement this in python? (doesn't have to be python but I would prefer it)

For the language server I could provide a CMakeLists.txt.

Ðаn
  • 10,934
  • 11
  • 59
  • 95
Gian Laager
  • 474
  • 4
  • 14
  • I'm not sure you want to do this honestly; the problem is that increasing that size "accidentally" is easy and can have high cost; so if someone anywhere makes a bigger derived instance, suddenly code "far away" starts requiring more memory. Imagine someone deriving with a class that is 10x larger than prior. Silently, costs to store all derived instances balloon. What I'd do is inject a `constexpr auto largest_derived = ##;` in the class definition, which people writing derived classes that trigger your static asserts must update manually. Then in code review it can be caught... – Yakk - Adam Nevraumont Jul 28 '21 at 14:16
  • It‘s infact exactly wat i want, that the library automatically changes the size because of a derived class in the code of the user, if i‘m doing it manually or automatically doesn’t matter. – Gian Laager Jul 28 '21 at 14:56

1 Answers1

0

I don't see why you need a language server. Using the define for the maximum size, you can check all classes against that constant, every time a new class is defined:

static_assert(sizeof(MyClass) < MAX_CLASS_SIZE);

(assumes C++ 17). This has the added benefit that you can see how large your classes are, the class size will not grow out of hand without a compiler error this way.

If you really want to compute the maximum size automatically, you can use something like this:

#define MAX(X,Y) X > Y ? X : Y
#define MAX_CLASS_SIZE MAX(sizeof(MyClass2), sizeof(MyClass3))
ScaledLizard
  • 171
  • 1
  • 9