For the code below, static SortOfSingleton instance;
works, but static SortOfSingleton instance();
creates four compilation errors:
- a block-scope function may only have extern storage class
- a reference of type "SortOfSingleton &" (not const-qualified) cannot be initialized with a value of type "SortOfSingleton ()"
- 'instance': static functions with block scope are illegal
- 'return': cannot convert from 'SortOfSingleton (__cdecl *)(void)' to 'SortOfSingleton &'
I do not understand those error messages. Isn't static SortOfSingleton instance();
creating a new instance by calling the empty constructor declared above? I wondered if I must not use ()
when assigning a reference, but there seems to be code that uses it, so that is probably not that.
What is the difference between instance();
and instance;
below?
Code:
class SortOfSingleton
{
public:
static SortOfSingleton& getInstance();
private:
SortOfSingleton();
SortOfSingleton(const SortOfSingleton&) = delete;
SortOfSingleton& operator=(const SortOfSingleton&) = delete;
};
SortOfSingleton::SortOfSingleton()
{
std::cout << "Creating new instance."<< std::endl;
}
SortOfSingleton& SortOfSingleton::getInstance()
{
static SortOfSingleton instance;
//static SortOfSingleton instance();
return instance;
}
int main()
{
auto& instance1 = SortOfSingleton::getInstance();