A singleton-like manager class, better design? - c++

I'm making a game engine and I'm using libraries for various tasks. For example, I use FreeType which needs to be initialized, get the manager and after I don't use it I have to de-initialize it. Of course, it can only be initialized once and can only be de-initialized if it has been initialized.
What I came up with (just an example, not "real" code [but could be valid C++ code]):
class FreeTypeManager
{
private:
FreeTypeManager() {} // Can't be instantiated
static bool initialized;
static TF_Module * module; // I know, I have to declare this in a separate .cpp file and I do
public:
static void Initialize()
{
if (initialized) return;
initialized = true;
FT_Initialize();
FT_CreateModule(module);
}
static void Deinitialize()
{
if (!initialized) return;
initialized = false;
FT_DestroyModule(module);
FT_Deinit();
}
};
And for every manager I create (FreeType, AudioManager, EngineCore, DisplayManager) it's pretty much the same: no instances, just static stuff. I can see this could be a bad design practice to rewrite this skeleton every time. Maybe there's a better solution.
Would it be good to use singletons instead? Or is there a pattern suiting for my problem?

If you still want the singleton approach (which kind of makes sense for manager-type objects), then why not make it a proper singleton, and have a static get function that, if needed, creates the manager object, and have the managers (private) constructor handle the initialization and handle the deinitialization in the destructor (though manager-type objects typically have a lifetime of the whole program, so the destructor will only be called on program exit).
Something like
class FreeTypeManager
{
public:
static FreeTypeManager& get()
{
static FreeTypeManager manager;
return manager;
}
// Other public functions needed by the manager, to load fonts etc.
// Of course non-static
~FreeTypeManager()
{
// Whatever cleanup is needed
}
private:
FreeTypeManager()
{
// Whatever initialization is needed
}
// Whatever private functions and variables are needed
};
If you don't want a singleton, and only have static function in the class, you might as well use a namespace instead. For variables, put them in an anonymous namespace in the implementation (source) file. Or use an opaque structure pointer for the data (a variant of the pimpl idiom).

There's another solution, which isn't exactly singleton pattern, but very related.
class FreeTypeManager
{
public:
FreeTypeManager();
~FreeTypeManager();
};
class SomeOtherClass
{
public:
SomeOtherClass(FreeTypeManager &m) : m(m) {}
private:
FreeTypeManager &m;
};
int main() {
FreeTypeManager m;
...
SomeOtherClass c(m);
}
The solution is to keep it ordinary c++ class, but then just instantiate it at the beginning of main(). This moves initialisation/destruction to a little different place. You'll want to pass references to FreeTypeManager to every class that wants to use it via constructor parameter.
Note that it is important that you use main() instead of some other function; otherwise you get scoping problems which require some thinking how to handle..

Related

using namespaces instead of singletons

Recently I posted a question on SO regarding usage of a class which carried a bit of separate functionality that it should've, ideally. I was recommended to learn about singleton pattern so that only one instance is created of the class and it manages the set of operations revolving around the data it encapsulates. You can see the question here - using Static Container for base and derived classes .
Now consider this code -
#include <iostream>
#include <string>
#include <unordered_map>
class A{
std::string id;
public:
A(std::string _i): id(_i){}
virtual void doSomething(){std::cout << "DoSomethingBase\n";}
};
class B : public A{
std::string name;
public:
B(std::string _n):name(_n), A(_n){}
void doSomething(){std::cout << "DoSomethingDerived\n";}
};
namespace ListA{
namespace{
std::unordered_map<std::string, A*> list;
}
void init(){
list.clear();
}
void place(std::string _n, A* a){
list[_n] = a;
}
}
int main() {
ListA::init();
ListA::place("b1", new B("b1"));
ListA::place("a1", new A("a1"));
return 0;
}
Ignoring the fact that I'm still using raw pointers which are leaking memory if program doesn't terminates as it is, is this a good alternative to using global static variables, or a singleton?
With regard to previous question, I've reorganized class A(base class) and class B(derived classes) independent of a namespace that manages a list of these objects. So is this a good idea, or a totally bad practice? Are there any shortcomings for it?
A good singleton implementation I was suggested was as follows -
class EmployeeManager
{
public:
static EmployeeManager& getInstance()
{
static EmployeeManager instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
EmployeeManager() {};
std::unordered_map<std::string, Employee&> list;
public:
EmployeeManager(EmployeeManager const&) = delete;
void operator=(const&) = delete;
void place(const std::string &id, Employee &emp){
list[id] = emp;
}
};
class Employee
{
public:
virtual void doSomething() = 0;
};
class Writer : public Employee
{
private:
std::string name_;
public:
Writer(std::string name) : name_(name) {};
void doSomething() { };
};
Honestly I've never tried singleton pattern and I'm shying away to use it directly since I've no prior experience and I would rather first use it in my pet projects.
is this a good alternative to using global static variables, or a singleton?
no, because you might encounter another problem: static initialization order fiasco. There are ways to fix it - but with functions with static variables - which looks just like singletons.
... but why do you need a global variables (even in namespaces) or singletons? In you first example, it would be perfectly fine if instead of namespace ListA you had struct ListA - plus remove that namespace{. Then you have:
int main() {
ListA list;
list.init();
list.place("b1", new B("b1"));
list.place("a1", new A("a1"));
}
and it looks fine.
Then your singleton aproach, once again - no need for it - create variable of type EmployeeManager in your main function, if you need to use it in some other class, then pass it by reference or pointer.
I'm not sure if you know that already, but you need to remember that Singleton really is a global variable with lazy initialization.
Lazy initialization is a tool to fix a problem of having the object initialized always at the time when you really want to use it - be it for some real-program function, or initializing another, dependent object. This is done to delay initialization until the first moment when you use the object.
The static object is simply initialized at the moment when it first appears to need to be created - however when this moment really is, is undefined, at least in C++.
You can replace lazy initialization with the static initialization, but you must ensure somehow that the initialization happens in defined order.
Defining variables inside the namespace is nothing else than declaring the variables globally. Namespaces are open, rules inside the namespace are the same as outside the namespace, except the symbol resolution.
What you can do to enforce ordered initialization is to create one global variable with all dependent global objects inside, in the form of struct that will contain all them as fields (not static fields!). Note though that the exact order of initialization will be only ensured between objects being fields of that structure, not between them and any other global objects.
Your question can be answered without any line of code, as it was answered by a lot of people in the past. Singletons are bad because your code will depend on one class and its implementation. What you want though is to have independent units which don't know about the implementations of the interfaces they talk to. Propagation of values / reference should (in fact it must be done for large maintainable systems) via reference passing from containing object to its child, an observer / event system or an event / message bus. Many frameworks use at leat two of these approaches ... I highly recommend sticking to best practices.

Design a class/type with only 1 possible instance - C++

I would like to have a class T that can generate only 1 instance in the whole program.
Now i know about std::unique_ptr but there are 2 problems:
it's limited to a scope ( but it's not a big issue ... )
it needs to be explicitly used, meaning that it's not part of the class or the type, it's just and handler and a special pointer, but it does not modify the design of my class.
now i would like to have class T designed in a way that not even by mistake the user can declare 2 instances in the same program and i can't rely on the fact that my user will declare an std::unique_ptr for T because i want to solve this by design.
right now i'm only thinking about how to make an implicit use of an unique_ptr in an elegant way, the problem is that i do not have any clue at the moment.
the other way around is to check if this class is handled by an unique_ptr but this check will make me lose an edge in terms of performances.
since having only 1 instance is really important, i see only 2 options in my case: 1) trying to solve this by design 2) throwing errors at compile time with some sort of check/macro.
I know that this looks trivial but with a design approach it's not, at least for me, so please help.
What you're looking for is called the Singleton pattern, and while it is widely considered by many (myself included) to be an anti-pattern, I will nonetheless show you the basic elements needed to build one.
Basically what you need to do is provide three things:
A static method which "gets" the one and only instance
A private constructor, so that nobody can ever instantiate it
(optional) A means by which the one and only instance is created before main starts
Here's the essential code:
class Singleton
{
public:
Singleton& get()
{
static Singleton me_;
return me_;
}
private:
Singleton() {};
};
I leave it to you to discover how to implement #3 above, and why you shouldn't be using a Singleton in the first place -- there are many reasons.
This is typically referred to as a Singleton.
See http://en.wikipedia.org/wiki/Singleton_pattern
The typical trick in C++ is to have a function which returns the singleton instance by reference, and make the constructor private.
Something like:
#include <iostream>
using namespace std;
class Foo
{
private:
Foo() : a(3) { a++; }
static Foo singleton;
int a;
public:
static Foo& getFoo() { return singleton; }
void doStuff() { cout<<"My a is: "<<a<<endl; }
};
Foo Foo::singleton;
int main(int argc, char** argv)
{
Foo::getFoo().doStuff();
Foo &foo = Foo::getFoo();
foo.doStuff();
//uncomment below to cause compile error
//Foo foo2;
}
Note that in real code you'll split this up into a header and a cpp file. In that case the
Foo Foo::singleton;
part must go in the cpp file.
You could have at least
static int count;
assert(count == 0);
count++;
in the constructor(s) of the singleton class. This don't ensure at compile time that your class is singleton, but at least it checks that at runtime.
And you could also make the constructor private, and have a static member function returning (once) a pointer to your instance, perhaps something like
class Singleton {
private:
Singleton() {
static int count;
assert(count == 0);
count++;
};
Singleton(Singleton&) = delete;
public:
static Singleton* the_instance() {
static Singleton* it;
if (!it) it = new Singleton();
return it;
}
};

Callback into singleton class

I am using a singleton class with a thread that calls into the singleton. I was asked during a review why I used the this pointer instead of the singleton instance.
My code with the suggested changes.
class myClass : public threadWrapper
{
public:
static myClass& instance()
{
static myClass instance;
return instance;
}
// This is the callback that I have implemented
static void callback(void *me)
{
if (me != NULL)
static_cast<myClass*>(me)->doCallback();
}
// This is the suggested callback
static void callback2(void *me)
{
instance().doCallback();
}
// caller gets instance and then calls initialise()
int initialise()
{
if (initialised)
return ERROR_ALREADY_INITIALISED;
// Initialise the class
// my thread startup call
// thread wrapper class initialisation that calls pthread_create that runs the callback method with this as a parameter
// priority is a global value that difines the relative priority of the various threads.
threadWrapper::Initialise(priority, callback, this);
initialised = true;
}
private:
myClass() : initialised(false) {;}
void doCallback(void);
bool initialised;
static const int
}
So is there any significant difference in speed between the two?
The threadWrapper is mandated in the existing code base, and I'm not allowed to use boost.
My justification was that if we needed to make this not a singleton then fewer changes would be required.
The speed difference will be pretty much nonexistent.
As for code quality, Singletons are quite horrendous and I personally would chuck out both forms, especially in a threaded environment. Assuming that it's too late for that, however.
The thing is, if you're gonna pass in a pointer to the object, why not just not make that object global in the first place? And if you are, it should at least be strongly typed. And then, you're just ... wrapping a member method in a static method? Why bother? Anyone who has a pointer to the class can just call the method on it in the first place. This is just insane.
Edit: If you're stuck with the existing design, then the second version is definitely better than the first and no slower. Even if you have existing code that depends on the Singleton, then it's absolutely better to refactor what you can to not depend on it.

Imitate a static constructor in C++

This a question related to the initialization of objects in C++.
I have a group of classes (not instances), inheriting from a common base class, and I need them to register info about themselves in a container (specifically a map) when the program starts.
The problem is that I need it to be dynamic. The container is defined in an independent project, different from the classes. I would prefer to avoid making multiple hard-coded versions of the library, one for each set of classes in each program that uses it.
I thought about having a static instance of a special class in each of these subclasses, that would make the registration in its constructor. However, I have found no way to guarantee that the container will be constructed before the construction of these objects.
I should also note that the information in the container about the subclasses should be available before any instance of these subclasses is created.
Is there a way to do this, or imitate a static constructor in C++ in general?
You are describing different problems all at once. On the particular issue of having some sort of static initialization, a simple approach is creating a fake class that will perform the registration. Then each one of the different classes could have a static const X member, the member will have to be defined in a translation unit, and the definition will trigger the instantiation of the instance and the registration of the class.
This does not tackle the hard problem, which is the initailization order fiasco. The language does not provide any guarantee on the order of initialization of objects in different translation units. That is, if you compile three translation units with such classes, there is no guarantee on the relative order of execution of the fake member. That is also applied to the library: there is no guarantee that the container in which you want to register your classes has been initialized, if such container is a global/static member attribute.
If you have access to the code, you can modify the container code to use static local variables, and that will be a step forward as to ensure the order of initialization. As a sketch of a possible solution:
// registry lib
class registry { // basically a singleton
public:
static registry& instance() { // ensures initialization in the first call
static registry inst;
return inst;
}
// rest of the code
private:
registry(); // disable other code from constructing elements of this type
};
// register.h
struct register {
template <typename T>
register( std::string name ) {
registry::instance().register( name, T (*factory)() ); // or whatever you need to register
}
};
// a.h
class a {
public:
static a* factory();
private:
static const register r;
};
// a.cpp
const register a::r( "class a", a::factory );
// b.h/b.cpp similar to a.h/a.cpp
Now in this case there is no definite order among the registration of the a and b classes, but that might not be an issue. On the other hand, by using a local static variable in the registry::instance function the initialization of the singleton is guaranteed to be performed before any call to the registry::register methods (as part of the first call to the instance method).
If you cannot make that change you are basically out of luck and you cannot guarantee that the registry will be instantiated before the other static member attributes (or globals) in other translation units. If that is the case, then you will have to postpone the registration of the class to the first instantiation, and add code to the constructor of each class to be registered that ensures that the class is registered before actual construction of the object.
This might or not be a solution, depending on whether other code creates objects of the type or not. In the particular case of factory functions (first one that came to mind), if nothing else is allowed to create objects of types a or b... then piggy backing registration on constructor calls will not be a solution either.
This is a candidate for the Singleton pattern. Basically, you want the container to be instantiated when the first instance of a subclass is instantiated. This can be facilitated by checking if the singleton pointer is NULL in the base-class constructor, and if so, then instantiate the container.
One idea is to pass a registration functor to the classes. Each descendant would execute the function to register. This functor could be passed in the constructor.
Example:
struct Registration_Interface
{
virtual void operator() (const std::string& component_name) = 0;
};
struct Base
{
};
struct Child1
: public Base
{
Child(Registration_Interface& registration_ftor)
{
//...
registration_ftor("Child1");
}
};
See: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14
One option is to construct the container lazily, when the first thing is added to it:
void AddToContainer(...) {
// Will be initialized the first time this function is called.
static Container* c = new Container();
c->Add(...);
}
The only way to "imitate" a static constructor is to explicitly call a function to perform your static initialization. There is no other way to run code pre-main just by linking in a module.
You might use an "initialise on first use" pattern, and then instantiate a dummy static instance to ensure initialisation as early as possible.
class cExample
{
public :
cExample() ;
// Static functions here
private :
static bool static_init ;
// other static members here
}
cExample::static init = false ;
cExample::cExample()
{
// Static initialisation on first use
if( !static_init )
{
// initialise static members
}
// Instance initialisation here (if needed)
}
// Dummy instance to force initialisation before main() (if necessary)
static cExample force_init ;
It is against OOP paradigm, but how about having your static members form a linked list guided by 2 global variables? You could do something like that:
ClassRegistrator *head = nullptr;
ClassRegistrator *tail = nullptr;
struct ClassRegistrator {
// ... Data that you need
ClassRegistrator *next;
ClassRegistrator(classData ...) {
if (!head)
head = tail = this;
else {
tail->next = this;
tail = this;
}
// ... Do other stuff that you need for registration
}
};
// The class you want to register
class MyClass {
static ClassRegistrator registrator;
}
ClassRegistrator MyClass::registrator(...); // Call the constructor
I believe the global variables, as they don't need have a constructor, but are just pure data, are guaranteed to be already initialised when you begin the execution of your code.
Obviously this is not thread-safe, etc, but should make your job done.

Global instance of a class in C++

As the title says. How would I create an instance of a class that is globally available(for example I have a functor for printing and i want to have a single global instance of this(though the possibility of creating more)).
Going to all the effort of making a singleton object using the usual pattern isn't addressing the second part of your question - the ability to make more if needed. The singleton "pattern" is very restrictive and isn't anything more than a global variable by another name.
// myclass.h
class MyClass {
public:
MyClass();
void foo();
// ...
};
extern MyClass g_MyClassInstance;
// myclass.cpp
MyClass g_MyClassInstance;
MyClass::MyClass()
{
// ...
}
Now, in any other module just include myclass.h and use g_MyClassInstance as usual. If you need to make more, there is a constructor ready for you to call.
First off the fact that you want global variables is a 'code smell' (as Per Martin Fowler).
But to achieve the affect you want you can use a variation of the Singleton.
Use static function variables. This means that variable is not created until used (this gives you lazy evaluation) and all the variables will be destroyed in the reverse order of creation (so this guarantees the destructor will be used).
class MyVar
{
public:
static MyVar& getGlobal1()
{
static MyVar global1;
return global1;
}
static MyVar& getGlobal2()
{
static MyVar global2;
return global2;
}
// .. etc
}
As a slight modification to the singleton pattern, if you do want to also allow for the possibility of creating more instances with different lifetimes, just make the ctors, dtor, and operator= public. That way you get the single global instance via GetInstance, but you can also declare other variables on the heap or the stack of the same type.
The basic idea is the singleton pattern, however.
Singleton is nice pattern to use but it has its own disadvantages. Do read following blogs by Miško Hevery before using singletons.
Singletons are Pathological Liars
Root Cause of Singletons
Where Have All the Singletons Gone?
the Singleton pattern is what you're looking for.
I prefer to allow a singleton but not enforce it so in never hide the constructors and destructors. That had already been said just giving my support.
My twist is that I don't use often use a static member function unless I want to create a true singleton and hide the constr. My usual approach is this:
template< typename T >
T& singleton( void )
{
static char buffer[sizeof(T)];
static T* single = new(buffer)T;
return *single;
}
Foo& instance = singleton<Foo>();
Why not use a static instance of T instead of a placement new? The static instance gives the construction order guarantees, but not destruction order. Most objects are destroyed in reverse order of construction, but static and global variables. If you use the static instance version you'll eventually get mysterious/intermittent segfaults etc after the end of main.
This means the the singletons destructor will never be called. However, the process in coming down anyway and the resources will be reclaimed. That's kinda tough one to get used to but trust me there is not a better cross platform solution at the moment. Luckily, C++0x has a made changes to guarantee destruction order that will fix this problem. Once your compiler supports the new standard just upgrade the singleton function to use a static instance.
Also, I in the actual implemenation I use boost to get aligned memory instead of a plain character array, but didn't want complicate the example
The simplest and concurrency safe implementation is Scott Meyer's singleton:
#include <iostream>
class MySingleton {
public:
static MySingleton& Instance() {
static MySingleton singleton;
return singleton;
}
void HelloWorld() { std::cout << "Hello World!\n"; }
};
int main() {
MySingleton::Instance().HelloWorld();
}
See topic IV here for an analysis from John Vlissides (from GoF fame).