Singleton - Impl. using static class member vs. static member variable - c++

Bring you two different implantation of singleton design pattern:
static class member
class SingletonCSM;
using SingletonCSMSp = std::shared_ptr < SingletonCSM > ;
class SingletonCSM
{
public:
~SingletonCSM() { spInstance = nullptr; }
static SingletonCSMSp GetInstance()
{
if (!spInstance)
spInstance = std::make_shared<SingletonCSM>();
return spInstance;
}
private:
SingletonCSM() {}
// will be intilized in the cpp: SingletonCSMSp SingletonCSM::spInstance = nullptr;
static SingletonCSMSp spInstance;
};
static member variable
class SingletonFSV;
using SingletonFSVSp = std::shared_ptr < SingletonFSV > ;
class SingletonFSV
{
public:
~SingletonFSV() {}
static SingletonFSVSp GetInstance()
{
static SingletonFSVSp spInstance = std::make_shared<SingletonFSV>();
return spInstance;
}
private:
SingletonFSV() {}
};
I always use the first impl. SingletonCSM. I came across, in our code, an impl. like SingletonFSV
Questions
Can we consider both impl. as a valid impl. of the design pattern?
Are both, functionally, the same?
Motivation
Background
Class SingletonFSV was implemented as a part of a DLL project. This DLL, compiled in VS 2013, is loaded in memory by an exe file and run.
Problem
I've upgrade my VS to VS 2015, compiled the DLL project and run the exe. All of a sudden, it crashed. While debugging, I've notice that the crash happened in the DLL itself. make_shared called withing GetInstance() returned nullptr and naturally caused segmentation fault.
Solution
I've changed SingletonFSV impl. to SingletonCSM and the crash stopped. make_shared returned a valid pointer and the problem was solved.
Question
I just don't understand what was the problem and why was it solved?

When you put a static variable inside a function it is created the first time the function is called so it is guaranteed to have been instantiated to all callers of the function.
Members that are declared static could be instantiated before or after you call your function because the initialization order between translation units is undefined. So a global object or static object could try to access a static member before its been initialized by the runtime system.
So to your questions:
Can we consider both impl. as a valid impl. of the design pattern?
Are both, functionally, the same?
No. Using a static member is dangerous because a caller to SingletonCSM::GetInstance() can access a non-created object if the nullptr initialization has not taken place before the call. The static function method is the recommended method because it guarantees initialization has completed for every caller.
I just don't understand what was the problem and why was it solved?
In your case moving to the more dangerous method appears to have stopped your crash. I can not explain why that is. But you may not have removed the problem, it may be that you have undefined behavior elsewhere that has simply stopped manifesting in this case but that may resurface later with a different change.

Related

Static Objects in a Class (Singleton)

I'm looking at two implementations of the Singleton design pattern.
I wanted to know how the second one works, in particular:
Why has the author chosen to return DB as a reference.
Why does the static class object DB in getDatabaseConnection() not need to be defined outside of the SingleDatabase class as such:
SingletonDatabase& SingletonDatabase::DB;
Does a static class object, like a static variable, only get created once (and is shared amongst all objects of the same class)?
Implementation
class SingletonDatabase {
private:
SingletonDatabase() {
std::cout << "Initializing database" << std::endl;
instanceCount++; // Used in testing later on.
}
public:
SingletonDatabase(const SingletonDatabase&) = delete;
SingletonDatabase& operator=(const SingletonDatabase&) = delete;
static SingletonDatabase& getDatabaseConnection() {
static SingletonDatabase DB;
return DB;
}
static int instanceCount;
};
int SingletonDatabase::instanceCount = 0;
I'm used to seeing the implementation with a static pointer, which the author mentioned is not thread safe. He prefers this method.
Thanks!
Why has the author chosen to return DB as a reference.
Instead of a reference, a pointer could have been used as well. The reference expresses better that the pointee is granted to exist. (Return by value instead would have corrupted the concept.)
Why does the static class object DB in getDatabaseConnection() not need to be defined outside of the SingleDatabase class as such:
SingletonDatabase& SingletonDatabase::DB;
It's not a member variable but a static variable with a local scope but the life-time of a static → granted to exist from first access until end of process.
SO: What is the lifetime of a static variable in a C++ function? (a little bit aged but still correct)
This would've been worked the same way in a plain function. That the surrounding function is a (static member function) is not that relevant concerning this.
Does a static class object, like a static variable, only get created once (and is shared amongst all objects of the same class)?
Yes.
To be correct, it's shared between any caller of this function.
Btw. this is known as Meyers Singleton:
FleCSI: Meyer’s Singleton → SO: C++ Singleton design pattern
SO: Is Meyers' implementation of the Singleton pattern thread safe?
To complete #Scheff's points:
I'm used to seeing the implementation with a static pointer, which the
author mentioned is not thread safe. He prefers this method.
As this Q/A shows, implementing the singleton pattern with pointers is not thread-safe.

Setting private member pointer to the same class as NULL?

I came across the following structure in a C++ library:
In myClass.h
class myClass {
public:
static myClass* Instance();
.
.
private:
static myClass* _instance;
.
.
};
and in myClass.cpp
myClass* myClass::_instance = NULL;
// followed by the all other functions..
myClass::myClass() {
.
.
}
myClass* myClass::Instance() {
if (_instance == NULL) {
.
.
}
.
.
}
So what is the use of making the _instance to be NULL pointer outside any function? And when is this line of code executed?
Thank you.
Edit:
Adding the main function. And the instance function in myClass.cpp that checks for the value of the pointer. Still don't understand when the pointer get set to NULL though.
int _tmain(int argc, T_CHAR* argv[]) {
myClass* instance = myClass::Instance();
.
.
.
return 0;
}
So what is the use of making the _instance to be NULL pointer outside any function?
Static data members usually have to be defined, in the namespace containing their class, in one source file; they are subject to the One Definition Rule, and so must have exactly one definition in any program that uses them. This is that definition.
Initialising it with NULL makes sure it's initially null, so that the Instance() function can determine whether the instance has been created yet. This isn't strictly necesssary since, like all static variables, it will be zero-initialised whether or not you explicitly provide an initialiser.
And when is this line of code executed?
During static initialisation, before any other code in the program; since it's a trivial type with a constant initialiser.
I have stumbled upon something like this once. It was something similar to singleton. The reason (as explained by the person doing it) was that he specifically wanted to initialize instance at the first getInstance() function call and he wanted to make sure that the _instance pointer will be at first initialized to NULL (and not some garbage from memory) so that the check
if (_instance == NULL)
in the function works properly.
I am not sure this is the case here, but it's possible.
myClass* myClass::_instance = NULL;
the code attempts to initialize the static member variable.
It's an initialisation, ensuring that the pointer starts life with the value NULL from the very beginning of the program.1
It gives the pointer an invalid, but recognisable and testable value before some useful pointer value is assigned to it later on during the program. This way, you can safely test the pointer to see whether it was yet given said useful value.
In this case, since you are showing a singleton, "later" means "when an instance of myClass is first requested" using some myClass::getInstancePlease() function that you have not shown.
It is more common to implement a singleton with a function-static instance, rather than a class-static pointer to some [probably dynamically-allocated] instance.
1 As an object with static storage duration, it would do so anyway; therefore, this initialisation is actually completely pointless beyond documenting programmers' intent.
Static keyword means it is being shared by all the objects that will be instantiated by the class. Hence you need to initialize it outside any function.Static states that it is a class variable shared between all the instance of the class. It is opposite to instance variables, which each instance has its own copy. To access a class variable, there are two ways. 1) a_class::static_variable 2) a_class a; a.static_variable. The initialization must go in the source file (.cpp) rather than in the header.
Because it is a static variable the compiler needs to create only one copy of it. If you don't, you get a link error. If that is in a header you will get a copy in every file that includes the header, so get multiply defined symbol errors from the linker.
Static data members are not part of objects of a given class type; they are separate objects. As a result, the declaration of a static data member is not considered a definition. The data member is declared in class scope, but definition is performed at file scope.

Creation of a Singleton object in initializer list causes an Access Violation (only Release Mode)

I do see a (for me) strange Access Violation exception. I'll try to reduce the problem as much as possible. I have a class A and a singleton object sing_. The code looks somehow like that:
class A {
A();
Sing& sing_;
}
A::A() : sing_(Sing::instance()){
call a method that creates a local copy of Singleton Sing.
....
}
The class Sing inherits from Singleton:
class Sing : public Singleton<Sing>{
friend class Singleton<Sing>;
....
}
Singleton itself looks like that (this is the implementation in the QuantLib library)
template <class T>
class Singleton : private boost::noncopyable {
public:
static T& instance();
protected:
Singleton() {}
};
template <class T>
T& Singleton<T>::instance() {
static std::map<Integer, boost::shared_ptr<T> > instances_;
#if defined(QL_ENABLE_SESSIONS)
Integer id = sessionId();
#else
Integer id = 0;
#endif
boost::shared_ptr<T>& instance = instances_[id];
if (!instance)
instance = boost::shared_ptr<T>(new T);
return *instance;
}
My project code is embedded in a Qt Gui environment. Starting it in Debug mode causes no troubles. Things change horribly when I try to start in Release mode. This is the main method:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
GUI w;
w.show();
w.setup(argc, argv);
return a.exec();
}
Finally the class GUI looks abbreviated like that:
class GUI : public QMainWindow
{
Q_OBJECT
public:
GUI(QWidget *parent = 0, Qt::WFlags flags = 0);
~GUI();
private:
boost::shared_ptr<A> a_;
};
When I start this code in Release mode the following happens:
A method called ___tmainCRTstartup() is invoked. Therein a method _WinMain is invoked.
Inside this method WinMain (even before the main method is invoked and the GUI object
is created) the constructor of A is called. This means that the member sing is going to be initialized.
sing_ is initialized during the call of Sing::instance(). Everything looks fine so far.
The constructor of A is executed. Therein a local refernce to the singleton object Sing is created. Calling Sing::instance() results in an access violation at that line
boost::shared_ptr<T>& instance = instances_[id];
When I look at instances_[id] at that place (debugging in Release mode) the map looks quite destroyed. That means there is one element in the map. But the key is not 0 but a very negativ integer and also the value looks strange.
I have absolutly no idea what goes wrong here.
Changing the member sing_ in A to be a static member fixes the problem:
class A {
A();
static Sing& sing_;
}
Sing& sing_ = Sing::instance();
A::A() {
call a method that creates a local copy of Singleton Sing.
....
}
That's of course nice but I'm really wondering what's the "big" difference between these two implementations. Why does the first way end in an Access Violation? Any hint is appreciated.
I'm not sure about the route of the problem, but I can offer some help in getting there:
First of all, the most common reasons why programs that run in debug fail in release (and vice versa):
In debug all memory is usually (most debuggers i know of) initialized as 0. So safety nullptr checks avoid errors. In release the memory isn't initialized, so you get garbage/random values.
Timing. Code optimizations, and the lack of debugging checks and settings (like setting everything to 0) make the code faster, so there's a different timing between threads.
Now back to your case. The reason why you see the variables as "destroyed" as you put it, is probably just because of the code optimizations.
Usually if you have code optimizations enabled, the compiler might decide to put some variables in the hardware registers, and not on the stack as they are intended.
This might cause the debugger to misinterpret some local variables. (Most commonly the *this pointer is stored in a register).
Now, the operator[] in a map shouldn't raise an exception. If the map doesn't have a value for that key, then it will be created.
So the only explanation I can think of is that the map itself is corrupt, so while it's trying to iterate through the map's nodes, it crashes.
This type of corruption is usually caused by 2 threads trying to alter the map at the same time.
This is possible in your case because there's no lock protection in that simple singleton implementation.
Another indication that this might be the case, is that when you make it static the problem is solved. Making the variable static causes the initiation of the object to occur much earlier, which might be just the timing you need to solve the threading race.

Class Members Over Exports

When Using DLLs or Code-injecting to be Specific
this is an example class only intended for explaining
class test
{
int newint1;
char newchararray[512];
void (*newfunction1)( int newarg1 );
int newfunction2( bool newarg1, char newarg2 )
{
return newint1;
}
} mynewclass1;
that covers most common elements that's included in classes
now when exporting this function to another DLL or application
and missed an element of those, either data member or function member, private or public
what happens or changed their order ?
and if each function is assigned it's value when Code-Injecting like
mynewclass1.newfunction1 = (void *)(newexportedfunction);
what's the happens in this case, if members of the class are pointers that are assigned after class construction and then missed one member or changed their order ?
I suppose that you forget to add a public: (:)
mynewclass1 is a statically initialized to zero at load time (unless you are working on very old version of windows).
if you add a constructor to your class behavior will become unpredictable because it is quite difficult to know when the static is effectively initialized (link-time dependencies at least).

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