I know that there is a million questions and answers about Singletons out there but I just can't seem to find the solution to this. So running the risk of negative votes, here's my problem:
I want to use this singleton implementation from Andrei Alexandrescu' Modern C++ Design:
header:
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...
By default, a class' members are private. To access your singleton, you need to make 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 the constructor (as you said in your title), it's the static member function that is supposed to return a reference to the singleton.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With