before i give you the file to play with, let me give you a few words of warning.
- don't descend from a singleton class. the reason for that is that there is only one instance and reference count variable. if you derive two classes from tsingleton, only one object will be created. the other class will reuse that object, which will be an instance of a different class. don't go down that road!
- you can't make singleton components for the simple reason of ownership. a component is owned by a form and one component can't be owned by several other components.
- remember that the constructor and destructor get called for each new reference as they are created and destroyed. don't initialize private variables in the constructor and don't free them in the destructor. instead, build that code into the
newinstanceand thefreeinstancemethods, as shown in the comments. - the order of adjusting ref_count in the two methods in conjunction with the rest of the code in those two methods is critical. it has to do with proper creation and destruction when something goes wrong. if your initialization code raises an exception, the order of doing things like shown above will make sure that the class is destroyed properly. alter this code at your peril!
link to file: codecentral entry 15083.
i'm sure you can find a few places where a singleton class comes in handy and now you have the tools to create your own! if you want to get in touch with me, my email is lasse@cintra.no.
happy programming!