digitalmars.D - How to make a singleton?
- nail <nail_member pathlink.com> Nov 19 2004
- J C Calvarese <jcc7 cox.net> Nov 19 2004
I tried to make a singleton for some particular class. As in C++ I made
constructor of this class protected, made method for instance access and so on.
All works fine until I try to instanciate my class outside the module where it
is defined. I was surprised but I didn't get any compile error after this trick.
How to prevent construction of class outside any module other then class owner?
Kernel kernel;
static this()
{
kernel = new Kernel;
}
class Kernel
{
protected:
this()
{
hInstance = GetModuleHandleA(null);
}
public:
.....
}
// another module snipet
int main ( char [] [] args )
{
Kernel k = new Kernel; // no error!
kernel.runMainLoop();
return 0;
}
Is it normaly?
----
nail
Nov 19 2004
nail wrote:I tried to make a singleton for some particular class. As in C++ I made constructor of this class protected, made method for instance access and so on. All works fine until I try to instanciate my class outside the module where it is defined. I was surprised but I didn't get any compile error after this trick. How to prevent construction of class outside any module other then class owner?
I think you're pretty close to your goal. Most importantly, you probably should upgrade to DMD 0.106. A recent bugfix allows privatizing this(). The following code works for me (i.e., it doesn't)... /* *** kernel.d *** */ import std.c.windows.windows; Kernel myKernel; static this() { myKernel = new Kernel; } class Kernel { protected: this() { void* hInstance = GetModuleHandleA(null); } public: void runMainLoop() {} } /* *** main.d *** */ import kernel; int main ( char [] [] args ) { Kernel k = new Kernel; /* it won't work in DMD 0.106 */ myKernel.runMainLoop(); return 0; } rem /* *** build.bat *** */ echo off dmd dmd main.d kernel.d main.exe pause erase *.obj erase *.map -- Justin (a/k/a jcc7) http://jcc_7.tripod.com/d/
Nov 19 2004








J C Calvarese <jcc7 cox.net>