|
From: Omar B. <oba...@gm...> - 2005-09-30 11:24:28
|
Hello, I am trying to make a singleton class using a reference to an object=
,
this is the code:
---- BEGIN main.cpp ---
01 #include <cstdio>
02 #include <iostream>
03
04 /*
05 * Singleton class
06 */
07 class Singleton1
08 {
09 int a,b,c;
10
11 // class constructor
12 Singleton1(){}
13 public:
14 // class destructor
15 ~Singleton1(){}
16 static Singleton1 &getHandle()
17 {
18 static Singleton1 s; // create a static variable to preserve its value
while the prgram is running
19 return s;
20 }
21 void setVars(int na, int nb, int nc)
22 {
23 a =3D na;
24 b =3D nb;
25 c =3D nc;
26 }
27 void printVars()
28 {
29 printf ("a: %d, b: %d, c: %d\n",a,b,c);
30 }
31
32 };
33
34 using namespace std;
35
36 int main(int argc, char *argv[])
37 {
38 Singleton1 sing =3D Singleton1::getHandle();
39
40 puts("vars a,b,c have trash:");
41 sing.printVars();
42
43 puts ("set vars to 1,2,3");
44 sing.setVars(1,2,3);
45
46 puts ("vars a,b,c should have 1,2,3, they have:");
47 sing.printVars();
48
49 puts ("Getting Singleton1 handler again...");
50 Singleton1 sing2 =3D Singleton1::getHandle();
51
52 puts("[using new handle] vars a,b,c should have 1,2,3, they have:");
53 sing2.printVars();
54
55 system("PAUSE");
56 return EXIT_SUCCESS;
57 }
---- EOF ---
Now, the first lines until 49 on the main function behave as expected but,
on line 50 I try to get again the handle to the singleton (via getHandle
static function) but it returns another new variable so, the values (1,2 an=
d
3 in this case) of the previous Singleton object are lost. Because of that
line 53 will print 0,0,0 and not 1,2,3.
Am I doing something wrong here?
Now, I can make it work if I change the getHandle function to return a
pointer ( Singleton1 * getHandle() ) and I change also the static variable
[line 18] to
18 static Singleton1 s =3D new Singleton1();
Of course I also change the references to the variable. But if I do it this
way there is no way I can delete the dynamically allocated object. And I
would like to do it using references and avoid pointers.
Any clue?
Cheers,
Omar.
--
Omar Baqueiro Espinosa
Computer Systems Engineer
Home: www.csc.liv.ac.uk/~omar/ <http://www.csc.liv.ac.uk/~omar/>
Calendar: calendar.yahoo.com/obaqueiro <http://calendar.yahoo.com/obaqueiro=
>
PGP Key available at:
www.csc.liv.ac.uk/~omar/pgp.html<http://www.csc.liv.ac.uk/~omar/pgp.html>
_____
|