Singletons...

From: Federico Carminati (Federico.Carminati@cern.ch)
Date: Wed Dec 01 1999 - 16:54:24 MET


Hi All,
  sorry for the lenghty message that follows. I could not make it any
shorter. Ok, I am playing with singletons and I have the following
implementation

rtest.h ----------------------------------------------------------------------

#include "TObject.h"
#include <stdio.h>

class AliSingleton : public TObject
{
private:
  static AliSingleton* fInstance;
  Int_t fData;
protected:
  AliSingleton() {printf("Singleton creator called\n");}
public:
  static AliSingleton* Instance() {
    if(!fInstance) fInstance = new AliSingleton;
    //    fInstance->Data()=101;
    return fInstance;
  }
  virtual ~AliSingleton() {
    printf("Singleton distructor called %p\n",fInstance);
  }
  Int_t& Data() { return fData;}
  void SetData(Int_t i) { fData=i;}

  ClassDef (AliSingleton,1)
};

rtest.cxx --------------------------------------------------------------------

#include "rtest.h"

AliSingleton* AliSingleton::fInstance=0;

ClassImp(AliSingleton)



Nothing to be very proud of...

Now I have the following main program

#include <TROOT.h>
#include <TFile.h>
#include "rtest.h"

TROOT root("TROOT","Application");

int main () {
  printf("Setting data\n");
  AliSingleton::Instance()->Data()=101;
  printf("data = %d\n",AliSingleton::Instance()->Data());
  AliSingleton::Instance()->SetData(99);
  printf("data = %d\n",AliSingleton::Instance()->Data());
  AliSingleton::Instance()->SetData(98);
  printf("data = %d\n",AliSingleton::Instance()->Data());
}

which gives the following result

Setting data
Singleton creator called
data = 101
data = 99
data = 98

If I run the program as a macro instead, I get

Setting data
Singleton creator called
data = 0
data = 99
data = 98

That is the statement AliSingleton::Instance()->Data()=101; is not obeyed
in the macro. Any idea? Thanks, 



                                            Federico Carminati



This archive was generated by hypermail 2b29 : Tue Jan 04 2000 - 00:43:43 MET