I am implementing the singleton pattern in C++ with the following implementation.
class Singleton
{
public:
~Singleton() { // some cleaning up implementation }
// Delete copy constructor and copy assignment.
Singleton(const Singleton& other) = delete;
Singleton& operator=(const Singleton& other) = delete;
static Singleton& GetInstance() { return s; }
private:
static Singleton s;
Singleton() { // some initialization implementation }
};
and I want to know if this is functionally different from a class that does not have a static member, but rather a static function which has a static variable in its own scope like this.
class Singleton
{
public:
~Singleton() { // some cleaning up implementation }
// Delete copy constructor and copy assignment.
Singleton(const Singleton& other) = delete;
Singleton& operator=(const Singleton& other) = delete;
static Singleton& GetInstance()
{
static Singleton s;
return s;
}
private:
Singleton() { // some initialization implementation }
};
As a follow up, does the GetInstance function need to return a reference Singleton&? Will the function attempt to copy construct the static variable into the return value, if the return is not a reference?