D
Daniel Kay
Hello,
currently I am reading the book "Effective C++ Third Edition" from Scott
Meyers. While Reading Item 4 (Make sure that objects are initialized
before they're used) I got an idea how to improve the way to implement
the Singlton Design Pattern.
This is the way I used to do it:
Singleton.h
----------
class Singleton {
public:
static Singleton* getInstance() {
if (!m_instance) {
m_instance = new Singleton();
}
return m_instance;
}
private:
Singleton() { }
~Singleton() { }
static Singleton* m_instance;
}
Singleton.cpp
-------------
Singleton* Singleton::m_instance = 0;
This is the way I am planning to do it in future:
Singleton.h
-----------
class Singleton {
public:
static Singleton* getInstance() {
static Singleton instance;
return &instance;
}
private:
Singleton() { }
~Singleton() { }
};
(Source is only showing the concept. I didn't compile it.)
I see the following pros:
- No potentional memory leak when process terminates.
- Less source code required.
- Not necessarely a .cpp file required for the static member.
Are there any cons I am missing?
Thanks for your thoughts,
Daniel Kay
currently I am reading the book "Effective C++ Third Edition" from Scott
Meyers. While Reading Item 4 (Make sure that objects are initialized
before they're used) I got an idea how to improve the way to implement
the Singlton Design Pattern.
This is the way I used to do it:
Singleton.h
----------
class Singleton {
public:
static Singleton* getInstance() {
if (!m_instance) {
m_instance = new Singleton();
}
return m_instance;
}
private:
Singleton() { }
~Singleton() { }
static Singleton* m_instance;
}
Singleton.cpp
-------------
Singleton* Singleton::m_instance = 0;
This is the way I am planning to do it in future:
Singleton.h
-----------
class Singleton {
public:
static Singleton* getInstance() {
static Singleton instance;
return &instance;
}
private:
Singleton() { }
~Singleton() { }
};
(Source is only showing the concept. I didn't compile it.)
I see the following pros:
- No potentional memory leak when process terminates.
- Less source code required.
- Not necessarely a .cpp file required for the static member.
Are there any cons I am missing?
Thanks for your thoughts,
Daniel Kay