-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSingleton.cpp
More file actions
71 lines (58 loc) · 1.65 KB
/
Singleton.cpp
File metadata and controls
71 lines (58 loc) · 1.65 KB
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
class S
{
public:
static S *getInstance()
{
static S *instance = new S(); // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {}; // Constructor? (the {} brackets) are needed here.
// C++ 03
// ========
// Dont forget to declare these two. You want to make sure they
// are unacceptable otherwise you may accidentally get copies of
// your singleton appearing.
// S(S const&); // Don't Implement
// void operator=(S const&); // Don't implement
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
S(S const&) = delete;
void operator=(S const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
void test();
};
//Another Example:
class StringSingleton
{
public:
std::string getString() const
{
return mString;
}
void setString(const std::string& newStr)
{
mString = newStr;
}
public:
static StringSingleton& instance()
{
static StringSingleton *instance = new StringSingleton;
return *instance;
}
private:
StringSingleton(){}
StringSingleton(const StringSingleton&);
const StringSingleton& operator=(const StringSingleton&);
~StringSingleton(){}
private:
std::string mString;
};