Delphi class variable for each class

I added class variables to the base class of the deep class hierarchy. This is an integer designed to count the number of instances created for each type of class. But I ran into a problem.

For example:

TBaseClass = class private class var fCreated: integer; public class function NewInstance: TObject; override; end; TDescendant = class(TBaseClass) end; ... class function TBaseClass.NewInstance: TObject; begin result := inherited NewInstance; inc(fCreated); end; 

I suggested that I could use the var class to store the number of instances created for each class , but that doesn't seem to be the case.

The TBaseClass.fCreated returns the same value as TDescendant.fCreated , changing one with the inspector changes the other, so it behaves as if fCreated is one global var.

I was expecting fCreated be supported by class type, right? What am I missing?

+6
source share
1 answer

You are missing nothing. Your analysis of how class variables work is correct. The var class is nothing more than a global variable spanned by the class.

One simple solution for you is to use a dictionary to count instances. A more hacky approach is to use my trick, which Hallvard Vassbotn bloggers talk about (ab) using VMT to store class-specific fields. You can read all about it here .

+8
source

Source: https://habr.com/ru/post/918348/


All Articles