www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - private ctor

reply "Miguel Ferreira Simões" <kobold netcabo.pt> writes:
I decided to do a singleton class (see code)... but i found that i could not
hide the ctor of the singleton derived classes.
Is there anyway to make it private? IMHO only this way the singleton class
makes sense.

class Singleton(T){
public:
 static T handle(){
  if (_instance === null){
   synchronized {
    if(!_handle) _handle = new T();
   }
  }
  return _handle;
 }

private:
  this() {}
  static T _handle;
};
May 31 2004
parent "Kris" <someidiot earthlink.dot.dot.dot.net> writes:
Private apparently does not yet apply to constructors, but let's hope Walter
will change that.

Additionally, you might consider using a static constructor for the
initialization:

static this()
{
    _handle = new T();
}

... which is perhaps a better way to avoid race conditions.

- Kris

"Miguel Ferreira Simões" <kobold netcabo.pt> wrote in message
news:c9fv3u$16hf$1 digitaldaemon.com...
 I decided to do a singleton class (see code)... but i found that i could

 hide the ctor of the singleton derived classes.
 Is there anyway to make it private? IMHO only this way the singleton class
 makes sense.

 class Singleton(T){
 public:
  static T handle(){
   if (_instance === null){
    synchronized {
     if(!_handle) _handle = new T();
    }
   }
   return _handle;
  }

 private:
   this() {}
   static T _handle;
 };

May 31 2004