Bonjour
j ai un comportement etrange avec mon implementation de l heritage d'un singleton...
voici la sortie du prog:
en fait le pointeur inst2 est egale a 0 et pourtant l appel d'un fonction de inst2 s'effectue correctement
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8 inst1 = 00354F30 inst2 = 00000000 Ce message est affiche par concretSingleton1 Bizarre qu'un pointeur NULL plante pas... Ce message est affiche par concretSingleton2 Ce message est affiche par concretSingleton1
hors le test de nullité du pointeur affiche bien le seul qui doit etre instancier...
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75 #include <iostream> class abstractSingleton { protected: static abstractSingleton* instance; abstractSingleton(){} virtual ~abstractSingleton(){} }; abstractSingleton* abstractSingleton::instance = NULL; class concretSingleton1 : public abstractSingleton { private: concretSingleton1() {} ~concretSingleton1() {} public: static abstractSingleton* GetInstance() { if ( abstractSingleton::instance == NULL ) { abstractSingleton::instance = new concretSingleton1(); } return abstractSingleton::instance; } void Message() { std::cout << "Ce message est affiche par concretSingleton1" << std::endl; } }; class concretSingleton2 : public abstractSingleton { private: concretSingleton2() {} ~concretSingleton2() {} public: static abstractSingleton* GetInstance() { if ( abstractSingleton::instance == NULL ) { abstractSingleton::instance = new concretSingleton2(); } return abstractSingleton::instance; } void Message() { std::cout << "Ce message est affiche par concretSingleton2" << std::endl; } }; int main() { concretSingleton1* inst1 = NULL; concretSingleton2* inst2 = NULL; inst1 = dynamic_cast<concretSingleton1*> (concretSingleton1::GetInstance()); inst2 = dynamic_cast<concretSingleton2*> (concretSingleton2::GetInstance()); std::cout << " inst1 = " << inst1 << std::endl; std::cout << " inst2 = " << inst2 << std::endl; if (inst1 != NULL) inst1->Message(); if (inst2 != NULL) inst2->Message(); std::cout << std::endl << "Bizarre qu'un pointeur NULL plante pas..." << std::endl; inst2->Message(); inst1->Message(); std::cin.ignore(); return 0; }
Partager