using namespaces instead of singletons - c++

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.

Related

A singleton-like manager class, better design?

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..

Calling function without declaring class

I want to achieve the "this line" in the following code. The most logical way is to set GetDog static, but then I cannot use "this". Is there a way to get around it? (not, since I was trying it out, there several lines not relevant to the question)
#include <iostream>
class Dog
{
public:
static int a;
Dog& GetDog(int k)
{
this->a = k;
return *this;
}
int bark()
{
return a*a;
}
};
int Dog::a=0;
int main()
{
Dog puppy;
int i = puppy.GetDog(4).bark();
cout<<i<<endl;
cout<<Dog::a<<endl;
//i = Dog::GetDog(6).bark(); //this line
return 0;
}
Not that doing this has much advantage (just that declaring a class is not required), but i saw it's used in some package I am using. I kind of want to understand how it is done.
class EXOFastFourierTransformFFTW
{
public:
static EXOFastFourierTransformFFTW& GetFFT(size_t length);
virtual void PerformFFT(const EXODoubleWaveform& aWaveform, EXOWaveformFT& aWaveformFT);
...
int main()
{
EXODoubleWaveform doublewf;
EXOWaveformFT wfFT;
...
EXOFastFourierTransformFFTW::GetFFT(doublewf.GetLength()).PerformFFT(doublewf,wfFT);
...
This static function usage also appears in Geant4, which probably is written by physicists, and so they might not do the wisest thing in programming. I still want to want if doing so has other advantages though.
From the vote down before I can see that this probably is not a regular method as I thought it is. Please comment so before doing it.
It seems that it is an implementation of the Meyers singleton.
I explain :
In the example given, the class EXOFastFourierTransformFFTW does not seem to have a constructor but return a reference to a EXOFastFourierTransformFFTW object.
And it looks like this implementation :
class Singleton
{
public:
static Singleton& Instance()
{
static Singleton obj;
return obj;
}
private:
Singleton();
};
From this book from Andrei Alexandrescu, it is said :
This simple and elegant implementation was first published by Scott Meyers; therefore, we'll refer to it as the Meyers Singleton.
The Meyers singleton relies on some compiler magic. A function-static object is initialized when the control flow is first passing its definition. Don't confuse static variables that are initialized at runtime[...]
[...]
In addition, the compiler generates code so that after initialization, the runtime support registers the variable for destruction.
So it good to use static to call a method from a class not instantiated but don't do it if it is not necessary... Here to represent a Singleton Pattern you have to.
But now if you want your class Dog look like that :
class Dog
{
public:
static Dog& GetDog(int k)
{
static Dog obj( k );
return obj;
}
int bark()
{
return a*a;
}
private:
int a;
Dog( int iA ) : a( iA ) {}
};
The static function usage is correct - it lets you use functions from classes without having an instance of the class. The FFT example you gave probably creates an instance within the static function. So in your case, you would instantiate Dog within the GetDog function (just be careful with returning references to local variables!).
You say that you can't use this if you make it static, which is true. But why would you want to access it without using an Object instance if you're going to need to use this at some point in the future? If it has a default value, or something like that, you could declare that elsewhere outside of the function as public static and then access it that way. If you clarify a little bit more as to what you're doing, I'll edit/remove this answer accordingly.

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;
}
};

What is the rationale for not having static constructor in C++?

What is the rationale for not having static constructor in C++?
If it were allowed, we would be initializing all the static members in it, at one place in a very organized way, as:
//illegal C++
class sample
{
public:
static int some_integer;
static std::vector<std::string> strings;
//illegal constructor!
static sample()
{
some_integer = 100;
strings.push_back("stack");
strings.push_back("overflow");
}
};
In the absense of static constructor, it's very difficult to have static vector, and populate it with values, as shown above. static constructor elegantly solves this problem. We could initialize static members in a very organized way.
So why doesn't' C++ have static constructor? After all, other languages (for example, C#) has static constructor!
Using the static initialization order problem as an excuse to not introducing this feature to the language is and always has been a matter of status quo - it wasn't introduced because it wasn't introduced and people keep thinking that initialization order was a reason not to introduce it, even if the order problem has a simple and very straightforward solution.
Initialization order, if people would have really wanted to tackle the problem, they would have had a very simple and straightforward solution:
//called before main()
int static_main() {
ClassFoo();
ClassBar();
}
with appropriate declarations:
class ClassFoo {
static int y;
ClassFoo() {
y = 1;
}
}
class ClassBar {
static int x;
ClassBar() {
x = ClassFoo::y+1;
}
}
So the answer is, there is no reason it isn't there, at least not a technical one.
This doesn't really make sense for c++ - classes are not first class objects (like in e.g. java).
A (static|anything) constructor implies something is constructed - and c++ classes aren't constructed, they just are.
You can easily achieve the same effect though:
//.h
struct Foo {
static std::vector<std::string> strings;
};
//.cpp
std::vector<std::string> Foo::strings(createStrings());
IMO there's just no need for one more syntactic way of doing this.
In which translation unit would the static objects be placed?
Once you account for the fact that statics have to be placed in one (and only one) TU, it's then not "very difficult" to go the rest of the way, and assign values to them in a function:
// .h
class sample
{
public:
static int some_integer;
static std::vector<std::string> strings;
};
//.cpp
// we'd need this anyway
int sample::some_integer;
std::vector<std::string> sample::strings;
// add this for complex setup
struct sample_init {
sample_init() {
sample::some_integer = 100;
sample::strings.push_back("stack");
sample::strings.push_back("overflow");
}
} x;
If you really want the code for sample_init to appear in the definition of class sample, then you could even put it there as a nested class. You just have to define the instance of it in the same place you define the statics (and after they've been initialized via their default constructors, otherwise of course you can't push_back anything).
C# was invented 15-20 years after C++ and has a completely different build model. It's not all that surprising that it offers different features, and that some things are less simple in C++ than in C#.
C++0x adds a features to make it easier to initialize vectors with some data, called "initializer lists"
You could get by with putting your "static" members in their own class with their own constructor that performs their initialization:
class StaticData
{
int some_integer;
std::vector<std::string> strings;
public:
StaticData()
{
some_integer = 100;
strings.push_back("stack");
strings.push_back("overflow");
}
}
class sample
{
static StaticData data;
public:
sample()
{
}
};
Your static data member is guaranteed to be initialized before you first try to access it. (Probably before main but not necessarily)
Static implies a function that is disassociated with an object. Since only objects are constructed, it is not apparent why a static constructor would have any benefit.
You can always hold an object in a static scope which has been constructed in a static block, but the constructor you would use would still be declared as non-static. There's no rule that indicates you can't call a non-static method from a static scope.
Finally, C++ / C defines the start of a program to be when the main function is entered. Static blocks are called prior to the entry of the main function as part of setting up the "environment" of the evaluated code. If your environment dictates full control over the set-up and tear-down, then it's easy to argue that it's not really some environmental fixture as much as an inherit procedural component of the program. I know that the last bit is sort of code-philosophy (and that it's rationale could be interpreted differently), but one shouldn't put critical code "before" the official start of an executable's handing off "full control" to the code written by the programmer.

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).