www.digitalmars.com Home | Search | C & C++ | D | DMDScript | News Groups | index | prev | next
Archives

D Programming
D
D.gnu
digitalmars.D
digitalmars.D.bugs
digitalmars.D.dtl
digitalmars.D.dwt
digitalmars.D.announce
digitalmars.D.learn
digitalmars.D.debugger

C/C++ Programming
c++
c++.announce
c++.atl
c++.beta
c++.chat
c++.command-line
c++.dos
c++.dos.16-bits
c++.dos.32-bits
c++.idde
c++.mfc
c++.rtl
c++.stl
c++.stl.hp
c++.stl.port
c++.stl.sgi
c++.stlsoft
c++.windows
c++.windows.16-bits
c++.windows.32-bits
c++.wxwindows

digitalmars.empire
digitalmars.DMDScript

digitalmars.D - How to make a singleton?

↑ ↓ ← nail <nail_member pathlink.com> writes:
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
↑ ↓ → J C Calvarese <jcc7 cox.net> writes:
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