Last active
April 4, 2018 06:34
-
-
Save aeciolevy/c84f4dcce00cb0cc639bfd8c6e28d224 to your computer and use it in GitHub Desktop.
Singleton C++ allowing Inheritance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Copyright (C) Aécio Levy | |
* Written by Aécio Levy - 16/03/2018 | |
* This program is free software: you can redistribute it and/or modify | |
* it under the terms of the GNU General Public License as published by | |
* the Free Software Foundation, either version 3 of the License, or | |
* (at your option) any later version. | |
*/ | |
#include "stdafx.h" | |
#include <iostream> | |
template <class T> | |
class Singleton { | |
protected: | |
// Static member variable | |
// The instace will be "stored"" | |
static T* mSingleton; | |
Singleton() {}; | |
virtual ~Singleton() {}; | |
public: | |
// Avoid Copy constructor | |
Singleton(const Singleton& copy) = delete; | |
// Avoid Copy assingment | |
Singleton& operator = (const Singleton& copy) = delete; | |
// Get the instance. If it is NULL create an instance | |
// Otherwise return the instance | |
static T* Instance() | |
{ | |
if (mSingleton == nullptr) | |
{ | |
mSingleton = new T(); | |
} | |
return mSingleton; | |
} | |
static void DeleteInstance() { | |
delete mSingleton; | |
} | |
}; | |
class Animal : public Singleton<Animal> { | |
public: | |
void Testing() { | |
std::cout << "Testing member variable" << std::endl; | |
} | |
}; | |
// a static member variable has to be initialized | |
// out of the constructor because they are not | |
// shared by object. They are initialized only once | |
Animal* Singleton<Animal>::mSingleton = nullptr; | |
int main() | |
{ | |
Animal* animal = Animal::Instance(); | |
animal->Testing(); | |
std::cin.get(); | |
Animal::DeleteInstance(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment