Reputation: 33
Code 1:
#include<iostream>
class Singleton
{
private:
static Singleton instance; //declaration of static variable
public:
static Singleton &GetInstance()
{
return instance;
}
void Hello()
{
std::cout << "Hello!";
}
};
Singleton Singleton::instance; //definition of static variable
int main()
{
Singleton::GetInstance().Hello();
}
Code 2:
#include <iostream>
class Singleton
{
public:
static Singleton &GetInstance()
{
static Singleton instance; //declaration of static variable
return instance;
}
void Hello()
{
std::cout << "Hello!";
}
};
int main()
{
Singleton::GetInstance().Hello();
}
In Code 1 we're required to define the static variable, but in Code 2, we just declared the static variable in the function Singleton::GetInstance&() and then returned it. Do the declaration and definition happen in the same line in Code 2? and why?
Upvotes: 3
Views: 1393
Reputation: 180245
[edit: this answer predates the C++14 tag on the question; it assumes C++17 or C++20]
The assumption is wrong:
class Singleton
{
private:
static inline Singleton instance; //definition of static variable
// ^^^^^^
You just need to give the compiler a warning.
Upvotes: 1
Reputation: 337
The static member variable instance
declared inside class Singleton
in Code 1 is a class variable.
This means that regardless of the state of different instances of class Singleton
, the state of static variable will remain the same for all objects/instances of that particular class. Hence, it needs to be defined outside the class.
(Just like a global variable which is available to function of all scopes.). A single copy of static member variable is allocated in memory even if you don't create any instance. Their definition persists through the entire file.
In Code 2, the static variable instance
is not a class variable but is simply a local variable inside a static member function. Hence there is no need for it to be defined outside since its scope is limited only to static Singleton &GetInstance()
function.
Upvotes: 5
Reputation: 1162
For classes static variables are stored well... staticly, so they are accessible between each instance of the class. As in, the same variable is accessible between classes. See https://en.wikipedia.org/wiki/Static_variable for what they are. In functions it wont make much sense to define them static as the function has no access outside of it.
In classes you do not need to define them as static. But in this case using a Singleton it is nice as it ensures everything in the program is working with one instance, as per Singleton design. (Does not guarantee thread safety)
Also static functions simply do not need a constructor to run, so they work as simple functions. They do not guarantee that you work with the same data.
Upvotes: 2