summaryrefslogtreecommitdiff
path: root/tests/utils/test3.cpp
blob: a07365a3c9debe9d36468dde0c3aaa289bf791ca (plain)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "Singleton.hpp"

#include <string>
#include <iostream>

using namespace std;

class Logger : public Singleton< Logger >
{
	public:		
		DECLARE_SINGLETON( Logger )

		void log( string s )
		{
			cout << s << endl;
		}
		
		friend class Singleton< Logger >;
	
	protected:
		Logger( )
		{
			cout << "Logger created" << endl;
		}
	
	public:	
		~Logger( )
		{
			cout << "Logger destroyed" << endl;
		}
};

/* this works, and two loggers can coexist, but they have different type 
class DerivedLogger : public Logger
{
	public:
		void log( string s )
		{
			cout << "derived " << s << endl;
		}
};
*/

class X : public Singleton< X >
{
	public:
		void doSomething( )
		{
			logger.log( "X is doing something" );
		}
		
		friend class Singleton< X >;
		
	protected:
		X ( ) : logger( Singleton< Logger >::instance( ) )
		{
			logger.log( "Creating singleton X" );
		}
	
	public:
		~X( )
		{
			logger.log( "Destroying singleton X" );
		}
	
	private:
		Logger &logger;
};

void f( ) 
{
	Logger &logger = Singleton< Logger >::instance( );
	logger.log( "bla" );
}

int main( void )
{
	f( );
	X &x = Singleton< X >::instance( );
	x.doSomething( );
	
	// this would copy the object, noncopyable ensure we have
	// only a private copy cnostructor
	//Logger l1 = Singleton< Logger >::instance( );

	// Logger anotherOne; this doesn't work, as expected

	// DerivedLogger anotherOne; the same here

	// see explanation above
	//DerivedLogger &l2 = Singleton< DerivedLogger >::instance( );
	//l2.log( "blu" );
		
	// we can't accidently destroy the logger
	//delete &logger;
	
	return 0;
}