יש כמה בעיות בקוד שנתת.
1. את ה-ctor יש לעשות protected ולא private, כדי שגם מי שיירש מה-singleton יהיה singleton בעצמו. 2. אפשר לעשות delete לסינגלטון שלך, ואז כל גישה נוספת תעיף את התוכנה. אפשרות אחת היא להפוך את ה-destructor ל-protected בעצמו ובכך למנוע delete, או לחילופין כתיבת ה-destructor ובתוכו instance=NULL. 3. לא ציינת שיש צורך באתחול של המשתנה הסטטי instance בקובץ ה-cpp. 4. עם הקוד שלך אפשר לעשות את הדבר הבא:
Logger MyAdditionalLogger = *(Logger::getInstance);
וזאת כיוון שנוצר לך default copy constructor שעליו לא שמרת. ___________________________________________________________________ להלן הדוגמה שלי ל-singleton:
#include <iostream> using namespace std; class singleton { protected: // Default constructor: defined as protected to disable things like new // or "singleton S". singleton() : m_n(5) {} // Copy constructor: declared as protected; not defined. // Code such as "singleton S = *(singleton::getInstance())" will not // compile. singleton(const singleton &rhs); public: ~singleton() { instance = NULL; } static singleton *getInstance() { if (!instance) instance = new singleton; return instance; } unsigned int GetNum() const { return m_n; } void SetNum(unsigned int n) { m_n = n; } // Data private: unsigned int m_n; static singleton *instance; }; // The static member. singleton *singleton::instance = NULL; int main() { cout << singleton::getInstance()->GetNum(); // Calling the destructor in order to clean up the memory. delete singleton::getInstance(); return (0); }