Using C ++ Singleton: Compiler complains about private constructor

I know there are a million questions and answers about Singletons, but I just can't find a solution to this. So risking negative votes, here is my problem:

I want to use this singleton implementation from Andrei Alexandrescu 'Modern C ++ Design:

Title:

class Singleton { static Singleton& Instance(); private: Singleton(){}; Singleton(const Singleton&){}; Singleton& operator=(const Singleton&){}; ~Singleton(){}; }; 

implementation:

 #include "s.hh" Singleton& Singleton::Instance() { static Singleton instance; return instance; } 

Test:

 #include "s.hh" int main(void) { Singleton& single = Singleton::Instance(); return 0; } 

Now,

 $g++ A.cc s.cc && ./a.out In file included from A.cc:1:0: s.hh: In function 'int main()': s.hh:3:19: error: 'static Singleton& Singleton::Instance()' is private static Singleton& Instance(); ^ A.cc:6:42: error: within this context Singleton& single = Singleton::Instance(); ^ 

What is wrong with that? I am stuck...

+4
source share
5 answers

By default, class members are private. To access your singleton, you need to do Singleton::Instance public:

 class Singleton { // here! public: static Singleton& Instance(); private: Singleton(){}; Singleton(const Singleton&){}; Singleton& operator=(const Singleton&){}; ~Singleton(){}; }; 

Note that this is not a constructor (as you said in your name), it is a static member function that should return a singleton reference.

+4
source

The default access for the class is private , so you need to explicitly make the Instance() method public :

 class Singleton { public: static Singleton& Instance(); private: // as before .... }; 

Alternatively, you can use a struct whose default access specifiers are publicly available:

 struct Singleton { static Singleton& Instance(); // public private: Singleton(){}; Singleton(const Singleton&){}; Singleton& operator=(const Singleton&){}; ~Singleton(){}; }; 
+3
source

The default access specifier for the private class. Add a method to the public access specifier.

 public: static Singleton& Instance(); 

Good reading:
What are access specifiers? Should I inherit confidential, secure, or open?

+3
source
 class S { public: static S& getInstance() { static S instance; return instance; } private: // other stuff here }; 
+2
source

Also do not make another destructor private.

 class Singleton { // here! public: static Singleton& Instance(); ~Singleton(){}; private: Singleton(){}; Singleton(const Singleton&){}; Singleton& operator=(const Singleton&){}; }; 
0
source

All Articles