Singleton's instance and scoped_ptr - c++

I have a singleton with a following structure:
// Hpp
class Root : public boost::noncopyable
{
public:
~Root();
static Root &Get();
void Initialize();
void Deinitialize();
private:
Root(); // Private for singleton purposes
static boost::scoped_ptr<Root> mInstance;
Manager1 *mManager1;
Manager2 *mManager2;
};
// Cpp
boost::scoped_ptr<Root> Root::mInstance;
Root::Root()
{
// [!!!]
mInstance = this;
// Managers are using `mInstance` in their constructors
mManager1 = new Manager1();
mManager2 = new Manager2();
mInstance->Initialize();
}
Root::~Root() { delete mManager1; delete mManager2; }
Root &Root::Get()
{
if (mInstance == nullptr) mInstance = boost::scoped_ptr<Root>(new Root());
return *mInstance;
}
The idea is to remove instance automatically when program exists. Look at line marked [!!!] : mInstance = this. I have to do this because mManager1 and mManager2 are using mInstance in their purposes in ctor.
The problem is how to use this with boost::scoped_ptr? In shared_ptr case there is enable_shared_from_this class from boost which allows to get what I need. But what to do in my case?

You can simply have the constructors take the Root as argument, and then pass this to them:
Root::Root() {
mManager1 = new Manager1(this);
mManager2 = new Manager2(this);
Initialize();
}
One additional advantage of this is that you don't get the other classes coupled to the singleton secretly.

Related

How to declare a global QWidget?

I want to have a class, which extends QWidget, that I can access in my whole program. I've already tried to declare it in the main.cpp (but this is obsiously not declared in the other files) or to to it after the class declaration (in this case, if I include the file more than once, I get the error multiple declaration).
Is it possible to the Widget as global, and if yes, how ?
Edit :
What I want to do is to write informations on an second window, which is an instance of the class Console (I have written that class).
Then, I have the class MainWindow, with the classes it contains; calculation_widget, and variable_widget, which contain respectively a list of calculations and variables.
I want to be able to write on the Console window from all those classes.
I don't recommend using this, but it would be better than a global pointer. In case you need your window(-s) only once in your application you could use the Singleton (Anti-)pattern.
This is the SingletonTemplate class.
#ifndef __CSingletonTemplate_H__
#define __CSingletonTemplate_H__
template <class T> class CSingletonTemplate
{
public:
static T* GetInstance()
{
if (m_Instance == 0)
{
m_Instance = new T();
}
return m_Instance;
}
static T& GetRefInstance()
{
if (m_Instance == 0)
{
m_Instance = new T();
}
return *m_Instance;
}
static void Release()
{
if (m_Instance != 0)
{
delete m_Instance;
m_Instance = 0;
}
}
protected:
CSingletonTemplate() { ; }; // Hidden constructor
CSingletonTemplate(CSingletonTemplate const&) { ; }; // Hidden copy constructor
CSingletonTemplate& operator=(CSingletonTemplate const&) { ; }; // Hidden assign operation
~CSingletonTemplate() { ; }; // Hidden destructor
private:
static T* m_Instance;
};
template <class T> T* CSingletonTemplate<T>::m_Instance = 0;
#endif // __CSingletonTemplate_H__
You use it by declaring a class like follows:
class MyWindow : public CSingletonTemplate<MyWindow>
{
friend class CSingletonTemplate<MyWindow>;
private:
MyWindow();
virtual ~MyWindow();
Q_DISABLE_COPY(MyWindow);
};
And you can use this class my calling MyWindow::GetInstance()->...
For more information about the Singleton Pattern visit: https://sourcemaking.com/design_patterns/singleton

C++ singleton template class crashes my program

I created a singleton pattern as a template class.
template <typename T>
class TemplateSingleton
{
protected:
TemplateSingleton() { }
virtual ~TemplateSingleton() { }
public:
static T * GetInstance()
{
if (m_pInstance == NULL)
m_pInstance = new T;
return m_pInstance;
};
static void FreeInstance()
{
if (m_pInstance != NULL)
{
delete m_pInstance;
m_pInstance = NULL;
}
};
private:
static T * m_pInstance;
};
template <typename T> T * TemplateSingleton<T>::m_pInstance = NULL;
And use inherited from child class.
This class can be used as a singleton by inheriting a template, or as a generic class if not inherited.
#define MAX_COUNT 8
class CDataHandler : public TemplateSingleton<CDataHandler>
{
public:
CDataHandler();
~CDataHandler();
...
private:
CDataObj m_clDataObj[MAX_COUNT]; // CDataObj *m_clDataObj ?
DWORD m_dwDataObjCount;
...
};
class CDataObj
{
public:
CDataObj();
~CDataObj();
...
private:
...
};
The code above is in a DLL, and the program is implemented to call only the instance constructor of CDataHandler.
And my program crashes and quits.
By the way, if I change CDataObj member variable from array to pointer, it works fine.
(In this case, new in the constructor of the CDataHandler, and delete in the destructor.)
Is there something wrong with this code?
Addition)
constructor and destructor code for CDataHandler :)
CDataHandler::CDataHandler()
: m_dwDataObjCount(0)
//, m_clDataObj(NULL)
{
// Do nothing
// m_clDataObj = new CDataObj[MAX_COUNT];
}
CDataHandler::~CDataHandler()
{
//if (m_clDataObj != NULL)
{
for (int i = 0; i < MAX_COUNT; i++)
{
m_clDataObj[i].Close();
}
// delete[] m_clDataObj;
// m_clDataObj = NULL;
}
}
Not sure what is causing your program to crash, but there are two potential problems in the code you posted.
First, you don't know when m_pInstance will be initialised to NULL. If you call GetInstance() during static data initialisation, m_pInstance might not yet be initialised to NULL and thus GetInstance() will return some invalid pointer. Look up "static data initialisation order fiasko" or something like this, there is a lot of information on this.
To avoid this, you can use local static variables, along the lines of:
T* GetInstance()
{
static T* t = new T{};
return t;
}
Second, you use a template for your singleton. That's okay, but you have to take care: If the definition of the class is available to more than one compilation unit, each of these compilation units will instantiate their own singleton, leaving you with multiple different instances depending on from which compilation unit you are accessing them.
To solve this, you can use extern template for a certain T in the DLL to tell others they should not instantiate this template specialisation and then compile an explicit template instantiation into the DLL to provide the implementation for everyone.

Singleton file static vs class private static

Is there any difference or specific advice when it comes to the following approaches for defining singletons?
In 1, the singleton object is a class private static, but in 2, it's a file static.
Note: m_initedObj1 is just there to show that class has state, and use case is to call this singleton->DoSomething() many times, without needing to init this object again.
1)
// header file
class Foo {
private:
static Foo* s_fooSingleton;
Foo();
Obj1 m_initedObj1;
public:
static Foo* Singleton();
static void ClearSingleton();
Bar DoSomething(...);
};
// cpp file
Foo* Foo::s_fooSingleton = nullptr;
Foo::Foo() { m_initedObj1 = InitObj1Somewhere(); }
/*static*/ Foo* Foo::Singleton()
{
if(!Foo::s_fooSingleton)
Foo::s_fooSingleton = new Foo();
return Foo::s_fooSingleton;
}
/*static*/ void Foo::ClearSingleton()
{
if(Foo::s_fooSingleton)
delete Foo::s_fooSingleton;
Foo::s_fooSingleton = nullptr;
}
Bar Foo::DoSomething(...) { // do something }
2)
// header file
class Foo {
private:
Foo();
Obj1 m_initedObj1;
public:
static Foo* Singleton();
static void ClearSingleton();
Bar DoSomething(...);
};
// cpp file
static Foo* s_fooSingleton = nullptr;
Foo::Foo() { m_initedObj1 = InitObj1Somewhere(); }
/*static*/ Foo* Foo::Singleton()
{
if(!s_fooSingleton)
s_fooSingleton = new Foo();
return s_fooSingleton;
}
/*static*/ void Foo::ClearSingleton()
{
if(s_fooSingleton)
delete s_fooSingleton;
s_fooSingleton = nullptr;
}
Bar Foo::DoSomething(...) { // do something }
As JerryGoyal states in the comments, in 2) other methods in the same .cpp file can modify s_fooSingleton.
On the other hand, they are not both thread-safe. If you don't really mind the clearing (calling ClearSingleton() explicitly), just go with the Scott Meyers' version. Otherwise, go with the double checked locking version.
It's really hard to ensure the safety in case of explicitly deleting. You always have to check whether it's deleted before you access it. If it's a multi-threaded executable, checking and using it must be atomic, because it can be deleted just after checking.
Double checked locking could be used to create and delete the singleton, which ensures you that there is only one instance at a time. Yet, it does not ensure the object really exist, since you may accidentally delete it.
You may use smart pointers to count references and delete it if no references exist.
Or even better, see this answer https://stackoverflow.com/a/15733545/1632887.
I just wouldn't delete it explicitly if I were you!
Maybe this will satisfy you more:
class MyClass1 {
private:
MyClass1(){}
public:
MyClass1& Instance() {
static MyClass1 theSingleInstance;
return theSingleInstance;
}
};
class MyClass2 {
private:
MyClass2() {}
public:
MyClass2* Instance() {
static MyClass2* theSingleInstance = new MyClass2;
return theSingleInstance;
}
};
class MyClass3 {
private:
MyClass3() {}
public:
MyClass3* Instance() {
static MyClass3 theSingleInstance;
return &theSingleInstance;
}
};

C++ singleton in constructor

Is this possible?
class A {
static A *instance = NULL;
public:
A () {
if (instance) {
this = instance;
} else {
instance = this;
}
}
}
Does it have leak memory?
Do I need to oveload new operator?
No. Overlooking your compiler errors, your class won't work.
#Galik has provided invaluable sources for how you'd actually want to construct a singleton. But let's look at yours.
class A {
static A *instance = NULL; // NULL isn't even a thing, but assuming you mean nullptr you can't assign a static like this
public:
A () {
if (instance) {
this = instance; // this can't be assigned
} else {
instance = this; // this is correct
}
}
};
Which would give you the following:
class A {
static A *instance;
public:
A () {
// if there's no instance, this is the one we'll use
if (!instance) {
instance = this;
}
}
};
A* A::instance = nullptr;
Which doesn't stop you from constructing more than one anyway.
Not possible. If the constructor is exposed and called, a new object of A is inevitably created. The most elegant and widely used implementations of C++ singleton classes use static methods to return the single static instance, while hiding (e.g. make private accessible) the constructor.
Here's an example:
class A {
private:
static A *instance_; // use nullptr since C++11
A() {}
public:
static A& instance() {
if (!instance_)
instance_ = new A();
return *instance_;
}
};
A* A::instance_ = nullptr;
You cannot assign a value for this

Using a Static Class function to create a Singleton object/instance

I am trying to create a static member function that returns a pointer to one instance of the class. Is this possible in C++?
class DynamicMemoryLog
{
// Singleton Class:
public:
static DynamicMemoryLog* CreateLog();
void AddIObject( IUnknown* obj );
void ReleaseDynamicMemory();
private:
// static DynamicMemoryLog* instance;
static bool isAlive; // used to determine is an instance of DynamicMemoryLog already exists
DynamicMemoryLog();
~DynamicMemoryLog();
std::vector <IUnknown*> iObjectList;
};
This function below should create a new instance of the class & return a pointer to that object, but the compiler will not allow me to define a static function of the class if it returns a pointer(I think thats why it wont compile?):
static DynamicMemoryLog* DynamicMemoryLog :: CreateLog()
{
// Post:
if ( !isAlive ) // ( instance == NULL; )
{
DynamicMemoryLog* instance = new DynamicMemoryLog();
return instance;
}
return NULL;
}
The particular error you're getting is that when implementing a static member function, you don't repeat the static keyword. Fixing this should resolve the error.
Independently, there's something a bit odd with your code. You claim that this object is a singleton, but each call to CreateLog will create a new instance of the class. Do you really want this behavior, or do you want there to be many copies? I'd suggest looking into this before proceeding.
Here's the simplest solution, but not thread-safe. For analysis in detail, have a look at this article.
class DynamicMemoryLog
{
public:
static DynamicMemoryLog* GetInstance();
private:
DynamicMemoryLog();
static DynamicMemoryLog* m_pInstance;
}
DynamicMemoryLog* DynamicMemoryLog::GetInstance()
{
if(!m_pInstance)
{
m_pInstance = new DynamicMemoryLog();
}
return m_pInstance;
}
I usually do something like this:
class Singleton
{
public:
static Singleton* get()
{
static Singleton instance;
return &instance;
}
};
This way you won't have any nasty memory management issues.