c++ singleton implementation STL thread safe - c++

I've been trying to implement a singleton with some C++11 features from STL. I read about a few implementations and I found this pretty good: http://silviuardelean.ro/2012/06/05/few-singleton-approaches/ I made a few changes and got the bellow code working on VS2013, but I still would like to know:
a) Is this implementation thread-safe?
b) Is it ok (good practice) to return a shared_ptr from GetInstance instead of a reference?
PS.: My singleton is ment to be an OpenGL interface (that's the reason for the name).
HandlerOpenGL.h
#pragma once
// STL headers
#include <memory> // shared_ptr
#include <mutex> // once_flag
// OpenGL Handler Singleton
class HandlerOpenGL
{
public:
// Constructor/Destructor interface
static std::shared_ptr<HandlerOpenGL> GetInstance(void); // Only way to access singleton
~HandlerOpenGL(void);
HandlerOpenGL(const HandlerOpenGL&) = delete; // Avoid any copy/move
HandlerOpenGL(HandlerOpenGL&&) = delete;
HandlerOpenGL& operator=(const HandlerOpenGL&) = delete;
HandlerOpenGL& operator=(HandlerOpenGL&&) = delete;
private:
// Hide construction method/variables
HandlerOpenGL(void); // Private to be created once
static std::shared_ptr<HandlerOpenGL> _instance;
static std::once_flag _flag;
};
HandlerOpenGL.cpp
// Own header
#include "HandlerOpenGL.h"
// STL headers
#include <memory> // shared_ptr, make_shared
#include <mutex> // once_flag, call_once
// instanciate static members
std::shared_ptr<HandlerOpenGL> HandlerOpenGL::_instance(nullptr);
std::once_flag HandlerOpenGL::_flag;
std::shared_ptr<HandlerOpenGL> HandlerOpenGL::GetInstance(void)
{
std::call_once(_flag, [](){ _instance.reset(new HandlerOpenGL); });
return _instance;
}
HandlerOpenGL::~HandlerOpenGL(void)
{
}
HandlerOpenGL::HandlerOpenGL(void)
{
}

I do not see a point of using shared_ptr there at all. If it is a singleton, it will not be copied. So why use shared_ptr?
I also believe, a Meyers singleton is so much easier to do, requires less typing, and doesn't rely on dynamic allocation, so I wonder why would anybody would do anything else.
Despite all this, I do not see a specific threading issues with that.

I think using static variable at member function better than static member.
This "_instance" will be created once method called.
HandlerOpenGL& HandlerOpenGL::GetInstance(void)
{
static HandlerOpenGL _instance;
return _instance;
}
look at this

Pro tip - if you do think you need a singleton, give it value semantics and encapsulate its singleton nature as a private implementation detail.
In the future you may realise you don't need a singleton after all. If you wrote the class with value semantics, you wont have to change any user code - only the private implementation of the singleton:
struct HandlerOpenGL
{
// public interface
// note - allow it to be copyable.
// interface exists as instance method
void do_some_graphics();
private:
struct impl;
// this line is the only clue that singletons are involved
static auto get_impl() -> impl&;
};
// implementation (private)
struct HandlerOpenGL::impl
{
// this class holds your static data such as library pointers
// it can be non-moveable etc
impl()
{
// _gfx_engine = init_gfx_engine();
// if (!_gfx_engine)
// throw std::runtime_error("gfx engine failed to init");
}
~impl()
{
// commented out so that this example compiles with no
// external dependencies
// if (_gfx_engine)
// deinit_gfx_engine(_gfx_engine);
}
// gfx_engine * _gfx_engine;
};
// this is the private singleton-fetcher
auto HandlerOpenGL::get_impl() -> impl&
{
static impl _;
return _;
}
// implement the interface
void HandlerOpenGL::do_some_graphics()
{
// fetch my internal singleton
auto& static_data = get_impl();
// use methods and data in static_data here
// gfx_draw_surface(static_data._gfx_engine);
}
// now you can use it like a value - and it's decoupled from logic
// a function that renders graphics on any appropriate graphics engine
template<class T>
void some_graphic_render(T handler)
{
handler.do_some_graphics();
}
int main()
{
auto gfx = HandlerOpenGL(); // created trivially - behaves like a value
auto gfx2 = gfx; // copies no problem at all
// use as an argument to allow ADL - allows decoupling and dependency injection
some_graphic_render(gfx);
some_graphic_render(HandlerOpenGL()); // can even create as needed. no performance cost
return 0;
}

Related

Is it better to declare the static singleton object outside of the static instance getter method? [duplicate]

In this thread, the following is said about singleton instances:
The static variable can be static to the GetInstance() function, or it can be static in the Singleton class. There's interesting tradeoffs there.
What are these trade-offs? I am aware that, if declared as a static function variable, the singleton won't be constructed until the function is first called. I've also read something about thread-safety, but am unaware of what exactly that entails, or how the two approaches differ in that regard.
Are there any other major differences between the two? Which approach is better?
In my concrete example, I have a factory class set up as a singleton, and I'm storing the instance as a static const field in the class. I don't have a getInstance() method, but rather expect the user to access the instance directly, like so: ItemFactory::factory. The default constructor is private, and the instance is allocated statically.
Addendum: how good of an idea is it to overload operator() to call the createItem() method for the singleton, such that Items can be created like so: ItemFactory::factory("id")?
What are these trade-offs?
This is the most important consideration:
The static data member is initialized during the static initialization at the start of the program. If any static object depends on the singleton, then there will be a static initialization order fiasco.
The function local static object is initialized when the function is first called. Since whoever depends on the singleton will call the function, the singleton will be appropriately initialized and is not susceptible to the fiasco. There is still a - very subtle - problem with the destruction. If a destructor of a static object depends on the singleton, but the constructor of that object does not, then you'll end up with undefined behaviour.
Also, being initialized on the first time the function is called, means that the function may be called after the static initialization is done and main has been called. And therefore, the program may have spawned multiple threads. There could be a race condition on the initialization of the static local, resulting in multiple instances being constructed. Luckily, since C++11, the standard guarantees that the initialization is thread safe and this tradeoff no longer exists in conforming compilers.
Thread safety is not an issue with the static data member.
Which approach is better?
That depends on what your requirements are and what version of the standard you support.
I vote for static function variable. The newer C++ standard require automatic thread safety for initialization of such variables. It's implemented in GNU C++ for about ten years already. Visual Studio 2015 also supports this. If you make a static pointer variable holding reference to your singleton object, you'll have to deal with thread issues manually.
In the other hand, if you make a static member pointer field like shown in in the snippet below, you will be able to change it from other static methods, maybe re-init this field with other instance upon handling request to change program configuration. However, the snippet below contains a bug just to remind you how difficult multithreading is.
class ItemFactory {
static std::atomic_flag initialized = ATOMIC_FLAG_INIT;
static std::unique_ptr<ItemFactory> theFactoryInstance;
public:
static ItemFactory& getInstance() {
if (!initialized.test_and_set(std::memory_order_acquire)) {
theFactoryInstance = std::make_unique<ItemFactory>();
}
return *theFactoryInstance;
}
};
I wouldn't advise you to implement your singleton as a global non-pointer variable initialized before entry to the main() function. Thread safety issues will go away along with implicit cache coherency overhead, but you're not able to control the initialization order of your global variables in any precise or portable way.
Anyway, this choice doesn't force any permanent design implications. Since this instance will reside in the private section of your class you may always change it.
I don't think overloading of operator() for a factory is a good idea. operator() have "execute" semantics while in factory it's gonna stand for "create".
What is the best approach to a singleton in c++?
Hide the fact that it's a singleton and give it value semantics.
How?
All singleton-ness ought to be an implementation detail. In this way, consumers of your class need not refactor their programs if you need to change the way you implement your singleton (or indeed if you decide that it should not really be a singleton after all).
Why ?
Because now your program never has to worry itself with references, pointers, lifetimes and whatnot. It just uses an instance of the object as if it were a value. Safe in the knowledge that the singleton will take care of whatever lifetime/resource requirements it has.
What about a singleton that releases resources when not in use?
no problem.
Here's an example of the two approaches hidden behind the facade of an object with value semantics.
imagine this use case:
auto j1 = jobbie();
auto j2 = jobbie();
auto j3 = jobbie();
j1.log("doh");
j2.log("ray");
j3.log("me");
{
shared_file f;
f.log("hello");
}
{
shared_file().log("goodbye");
}
shared_file().log("here's another");
shared_file f2;
{
shared_file().log("no need to reopen");
shared_file().log("or here");
shared_file().log("or even here");
}
f2.log("all done");
where a jobbie object is just a facade for a singleton, but the shared_file object wants to flush/close itself when not in use.
so the output should look like this:
doh
ray
me
opening file
logging to file: hello
closing file
opening file
logging to file: goodbye
closing file
opening file
logging to file: here's another
closing file
opening file
logging to file: no need to reopen
logging to file: or here
logging to file: or even here
logging to file: all done
closing file
We can achieve this using the idiom, which I'll call 'value-semantics-is-a-facade-for-singleton':
#include <iostream>
#include <vector>
// interface
struct jobbie
{
void log(const std::string& s);
private:
// if we decide to make jobbie less singleton-like in future
// then as far as the interface is concerned the only change is here
// and since these items are private, it won't matter to consumers of the class
struct impl;
static impl& get();
};
// implementation
struct jobbie::impl
{
void log(const std::string& s) {
std::cout << s << std::endl;
}
};
auto jobbie::get() -> impl& {
//
// NOTE
// now you can change the singleton storage strategy simply by changing this code
// alternative 1:
static impl _;
return _;
// for example, we could use a weak_ptr which we lock and store the shared_ptr in the outer
// jobbie class. This would give us a shared singleton which releases resources when not in use
}
// implement non-singleton interface
void jobbie::log(const std::string& s)
{
get().log(s);
}
struct shared_file
{
shared_file();
void log(const std::string& s);
private:
struct impl;
static std::shared_ptr<impl> get();
std::shared_ptr<impl> _impl;
};
// private implementation
struct shared_file::impl {
// in a multithreaded program
// we require a condition variable to ensure that the shared resource is closed
// when we try to re-open it (race condition)
struct statics {
std::mutex m;
std::condition_variable cv;
bool still_open = false;
std::weak_ptr<impl> cache;
};
static statics& get_statics() {
static statics _;
return _;
}
impl() {
std::cout << "opening file\n";
}
~impl() {
std::cout << "closing file\n";
// close file here
// and now that it's closed, we can signal the singleton state that it can be
// reopened
auto& stats = get_statics();
// we *must* use a lock otherwise the compiler may re-order memory access
// across the memory fence
auto lock = std::unique_lock<std::mutex>(stats.m);
stats.still_open = false;
lock.unlock();
stats.cv.notify_one();
}
void log(const std::string& s) {
std::cout << "logging to file: " << s << std::endl;
}
};
auto shared_file::get() -> std::shared_ptr<impl>
{
auto& statics = impl::get_statics();
auto lock = std::unique_lock<std::mutex>(statics.m);
std::shared_ptr<impl> candidate;
statics.cv.wait(lock, [&statics, &candidate] {
return bool(candidate = statics.cache.lock())
or not statics.still_open;
});
if (candidate)
return candidate;
statics.cache = candidate = std::make_shared<impl>();
statics.still_open = true;
return candidate;
}
// interface implementation
shared_file::shared_file() : _impl(get()) {}
void shared_file::log(const std::string& s) { _impl->log(s); }
// test our class
auto main() -> int
{
using namespace std;
auto j1 = jobbie();
auto j2 = jobbie();
auto j3 = jobbie();
j1.log("doh");
j2.log("ray");
j3.log("me");
{
shared_file f;
f.log("hello");
}
{
shared_file().log("goodbye");
}
shared_file().log("here's another");
shared_file f2;
{
shared_file().log("no need to reopen");
shared_file().log("or here");
shared_file().log("or even here");
}
f2.log("all done");
return 0;
}

Singleton instance as static field vs. static variable in getInstance() method

In this thread, the following is said about singleton instances:
The static variable can be static to the GetInstance() function, or it can be static in the Singleton class. There's interesting tradeoffs there.
What are these trade-offs? I am aware that, if declared as a static function variable, the singleton won't be constructed until the function is first called. I've also read something about thread-safety, but am unaware of what exactly that entails, or how the two approaches differ in that regard.
Are there any other major differences between the two? Which approach is better?
In my concrete example, I have a factory class set up as a singleton, and I'm storing the instance as a static const field in the class. I don't have a getInstance() method, but rather expect the user to access the instance directly, like so: ItemFactory::factory. The default constructor is private, and the instance is allocated statically.
Addendum: how good of an idea is it to overload operator() to call the createItem() method for the singleton, such that Items can be created like so: ItemFactory::factory("id")?
What are these trade-offs?
This is the most important consideration:
The static data member is initialized during the static initialization at the start of the program. If any static object depends on the singleton, then there will be a static initialization order fiasco.
The function local static object is initialized when the function is first called. Since whoever depends on the singleton will call the function, the singleton will be appropriately initialized and is not susceptible to the fiasco. There is still a - very subtle - problem with the destruction. If a destructor of a static object depends on the singleton, but the constructor of that object does not, then you'll end up with undefined behaviour.
Also, being initialized on the first time the function is called, means that the function may be called after the static initialization is done and main has been called. And therefore, the program may have spawned multiple threads. There could be a race condition on the initialization of the static local, resulting in multiple instances being constructed. Luckily, since C++11, the standard guarantees that the initialization is thread safe and this tradeoff no longer exists in conforming compilers.
Thread safety is not an issue with the static data member.
Which approach is better?
That depends on what your requirements are and what version of the standard you support.
I vote for static function variable. The newer C++ standard require automatic thread safety for initialization of such variables. It's implemented in GNU C++ for about ten years already. Visual Studio 2015 also supports this. If you make a static pointer variable holding reference to your singleton object, you'll have to deal with thread issues manually.
In the other hand, if you make a static member pointer field like shown in in the snippet below, you will be able to change it from other static methods, maybe re-init this field with other instance upon handling request to change program configuration. However, the snippet below contains a bug just to remind you how difficult multithreading is.
class ItemFactory {
static std::atomic_flag initialized = ATOMIC_FLAG_INIT;
static std::unique_ptr<ItemFactory> theFactoryInstance;
public:
static ItemFactory& getInstance() {
if (!initialized.test_and_set(std::memory_order_acquire)) {
theFactoryInstance = std::make_unique<ItemFactory>();
}
return *theFactoryInstance;
}
};
I wouldn't advise you to implement your singleton as a global non-pointer variable initialized before entry to the main() function. Thread safety issues will go away along with implicit cache coherency overhead, but you're not able to control the initialization order of your global variables in any precise or portable way.
Anyway, this choice doesn't force any permanent design implications. Since this instance will reside in the private section of your class you may always change it.
I don't think overloading of operator() for a factory is a good idea. operator() have "execute" semantics while in factory it's gonna stand for "create".
What is the best approach to a singleton in c++?
Hide the fact that it's a singleton and give it value semantics.
How?
All singleton-ness ought to be an implementation detail. In this way, consumers of your class need not refactor their programs if you need to change the way you implement your singleton (or indeed if you decide that it should not really be a singleton after all).
Why ?
Because now your program never has to worry itself with references, pointers, lifetimes and whatnot. It just uses an instance of the object as if it were a value. Safe in the knowledge that the singleton will take care of whatever lifetime/resource requirements it has.
What about a singleton that releases resources when not in use?
no problem.
Here's an example of the two approaches hidden behind the facade of an object with value semantics.
imagine this use case:
auto j1 = jobbie();
auto j2 = jobbie();
auto j3 = jobbie();
j1.log("doh");
j2.log("ray");
j3.log("me");
{
shared_file f;
f.log("hello");
}
{
shared_file().log("goodbye");
}
shared_file().log("here's another");
shared_file f2;
{
shared_file().log("no need to reopen");
shared_file().log("or here");
shared_file().log("or even here");
}
f2.log("all done");
where a jobbie object is just a facade for a singleton, but the shared_file object wants to flush/close itself when not in use.
so the output should look like this:
doh
ray
me
opening file
logging to file: hello
closing file
opening file
logging to file: goodbye
closing file
opening file
logging to file: here's another
closing file
opening file
logging to file: no need to reopen
logging to file: or here
logging to file: or even here
logging to file: all done
closing file
We can achieve this using the idiom, which I'll call 'value-semantics-is-a-facade-for-singleton':
#include <iostream>
#include <vector>
// interface
struct jobbie
{
void log(const std::string& s);
private:
// if we decide to make jobbie less singleton-like in future
// then as far as the interface is concerned the only change is here
// and since these items are private, it won't matter to consumers of the class
struct impl;
static impl& get();
};
// implementation
struct jobbie::impl
{
void log(const std::string& s) {
std::cout << s << std::endl;
}
};
auto jobbie::get() -> impl& {
//
// NOTE
// now you can change the singleton storage strategy simply by changing this code
// alternative 1:
static impl _;
return _;
// for example, we could use a weak_ptr which we lock and store the shared_ptr in the outer
// jobbie class. This would give us a shared singleton which releases resources when not in use
}
// implement non-singleton interface
void jobbie::log(const std::string& s)
{
get().log(s);
}
struct shared_file
{
shared_file();
void log(const std::string& s);
private:
struct impl;
static std::shared_ptr<impl> get();
std::shared_ptr<impl> _impl;
};
// private implementation
struct shared_file::impl {
// in a multithreaded program
// we require a condition variable to ensure that the shared resource is closed
// when we try to re-open it (race condition)
struct statics {
std::mutex m;
std::condition_variable cv;
bool still_open = false;
std::weak_ptr<impl> cache;
};
static statics& get_statics() {
static statics _;
return _;
}
impl() {
std::cout << "opening file\n";
}
~impl() {
std::cout << "closing file\n";
// close file here
// and now that it's closed, we can signal the singleton state that it can be
// reopened
auto& stats = get_statics();
// we *must* use a lock otherwise the compiler may re-order memory access
// across the memory fence
auto lock = std::unique_lock<std::mutex>(stats.m);
stats.still_open = false;
lock.unlock();
stats.cv.notify_one();
}
void log(const std::string& s) {
std::cout << "logging to file: " << s << std::endl;
}
};
auto shared_file::get() -> std::shared_ptr<impl>
{
auto& statics = impl::get_statics();
auto lock = std::unique_lock<std::mutex>(statics.m);
std::shared_ptr<impl> candidate;
statics.cv.wait(lock, [&statics, &candidate] {
return bool(candidate = statics.cache.lock())
or not statics.still_open;
});
if (candidate)
return candidate;
statics.cache = candidate = std::make_shared<impl>();
statics.still_open = true;
return candidate;
}
// interface implementation
shared_file::shared_file() : _impl(get()) {}
void shared_file::log(const std::string& s) { _impl->log(s); }
// test our class
auto main() -> int
{
using namespace std;
auto j1 = jobbie();
auto j2 = jobbie();
auto j3 = jobbie();
j1.log("doh");
j2.log("ray");
j3.log("me");
{
shared_file f;
f.log("hello");
}
{
shared_file().log("goodbye");
}
shared_file().log("here's another");
shared_file f2;
{
shared_file().log("no need to reopen");
shared_file().log("or here");
shared_file().log("or even here");
}
f2.log("all done");
return 0;
}

How to access stuff in one function from another, called from third in c++

I have this code:
void Forms::login() {
LoginForm *loginForm = new LoginForm;
loginForm->show();
}
void Forms::startGame() {
WorldForm *worldForm = new WorldForm;
worldForm->show();
loginForm->hide();
}
So, I am trying to tie all logics to one separate file, like logics.cpp. First I was using just regular functions, but I couldn't get access to loginForm from startGame (cause I cannot simply add this into .h file, this crashes all program, don't ask why - Qt stuff. These types are QWidgets). Now what I need is:
How to add declaration of WorldForm & LoginForm to the root of class Forms (or to the header file), I cannot do this.
The final goal is to call startGame() (or, in this case, Forms::startGame() as static function) from ANOTHER class in another file, and startGame() should be able to hide loginForm, as it seemed above.
I can't do it even like this:
void Forms::world(int a) {
WorldForm *worldForm = new WorldForm;
if(a==0) {
worldForm->show();
}else{
worldForm->hide();
}
}
Because I need worldForm created only once, and this will create lots of instances 1 for each call.
Here's my code: https://github.com/ewancoder/game
What you're looking for are member variables and the singleton pattern done in the style of QApplication.
What you seem to be doing is declaring global variables of a widget type:
// interface (.h)
extern QWidget myWidget;
// implementation (.cpp)
QWidget myWidget;
This will never work, since the construction of such an object happens before main() starts! This is the key difference you have between Delphi and C++. In Delphi, you must call constructors of objects yourself. In C++, it's done automatically - and for global variables, everything is constructed by the time main() gets to execute. You need to use pointers instead.
The Forms class can be declared and implemented as shown below.
The class isn't copyable since the QScopedPointer isn't copyable, so we should make it explicit for the human reader. There's no good reason for this class to be copyable anyway, even if, say, we used a QSharedPointer instead.
The QScopedPointer smart pointer is used so that the forms don't leak. The destructor for QScopedPointer automatically frees the allocated form, if any. It can be used as a bool, it's true when it is non-null.
The class enforces an invariant that there is only one instance of it. That instance should be constructed in the main() function, after QApplication. You can access this instance from anywhere by using the static Forms::instance() method.
For example, in LoginForm::on_loadButton_clicked(), you'd use
Forms::instance()->world();
// core.h - interface
#include <QScopedPointer>
class LoginForm;
class WorldForm;
class Forms {
Q_DISABLE_COPY(Forms)
QScopedPointer<LoginForm> m_loginForm;
QScopedPointer<WorldForm> m_worldForm;
static Forms * m_instance; // declaration
public:
Forms();
~Forms();
static Forms * instance();
void login(int act = 0);
void world();
};
// forms.cpp - implementation
#include "core.h"
#include "Forms/loginform.h"
#include "Forms/worldform.h"
Forms * Forms::m_instance = 0; // definition
// The runtime default-constructs static class members, so technically
// the explicit initialization to a null pointer is not necessary.
void Forms::login(int act) {
if (!m_loginForm) m_loginForm.reset(new LoginForm);
switch(act) {
case 1:
m_loginForm->hide();
break;
default:
m_loginForm->show();
}
}
void Forms::world() {
if (!m_worldForm) m_worldForm.reset(new WorldForm);
m_worldForm->show();
}
Forms::Forms() {
Q_ASSERT(! m_instance);
m_instance = this;
}
Forms::~Forms() {
m_instance = 0;
}
Forms * Forms::instance() {
return m_instance;
}
// main.cpp
#include <QApplication>
#include "Classes/core.h"
int main(int argc, char *argv[]) {
QApplication game(argc, argv);
Forms forms;
forms.login();
return game.exec();
// The local object instances are destructed in C++-generated-code.
// The order of destruction is opposite to the order of definition.
// The compiler puts the following code "here":
// forms.~Forms();
// game.~QApplication();
}
So, one might ask, why just not make everything in the Forms class static and be done with it? It's not really possible due to the lifetime of static class member variables. Such members are constructed before main() starts, and destructed after main() ends. That's a big problem, since:
You can't leverage smart pointers to widgets, since they will be deleted when QApplication isn't there anymore, and that's not allowed. You can reset() those pointers manually, but that really defeats the purpose of smart pointers. Smart pointers are there so that you don't have to manage memory manually.
Since there's no instance of the Forms class - it's just a wrapper for static members - the destructor won't ever get invoked, and you can't leverage C++ to clean up the members automatically.
The most you can do is make all of the methods static, but not the member variables. So, this would still be OK, but makes the method implementations cumbersome:
class Forms {
Q_DISABLE_COPY(Forms)
QScopedPointer<LoginForm> m_loginForm;
QScopedPointer<WorldForm> m_worldForm;
static Forms * m_instance;
public:
Forms();
~Forms();
static Forms * instance();
static void login(int act = 0);
static void world();
};
void Forms::login(int act) {
Forms * inst = instance();
if (!inst->m_loginForm) inst->m_loginForm.reset(new LoginForm);
...
}
But this certainly is wrong:
// WRONG
class Forms {
static QScopedPointer<LoginForm> m_loginForm;
static QScopedPointer<WorldForm> m_worldForm;
public:
static void login(int act = 0);
static void world();
};
It's wrong since the scoped pointers get destructed, and thus the forms are deleted, after main() ends. You're not allowed to do anything with widgets - not even destruct them - with no QApplication around.
To work around that, you'd need to explicitly free the form instances in a static destructor-like method, that you must manually call to delete the forms. Your main would then become Delphi written in C++ syntax. You have a strong bias towards Delphi idioms. Those idioms don't belong in C++ -- you must unlearn them. C++ compilers do a whole lot of code generation that required manual labor in Delphi. You are expected to leverage that.
// AWKWARD: Delphi code in C++ syntax
int main(int argc, char *argv[]) {
QApplication game(argc, argv);
Forms::login();
int rc = game.exec();
Forms::destroy();
return rc;
}
// BRAINDEAD: Delphi code in C++ syntax
class Forms {
static QScopedPointer<LoginForm> m_loginForm;
static QScopedPointer<WorldForm> m_worldForm;
public:
static void login(int act = 0);
static void world();
static void destroy();
};
This hopefully explains why C++ is a much more powerful language than Delphi. In Delphi, you have to worry about a lot of things that the C++ compiler takes care of, preventing you from forgetting about something important like freeing memory or releasing other resources.

How to change a behavior for all instances of a class in a header only class

For a class, which is only defined in a header, I need a special behavior of one method for all instance of the class. It should be depending on a default value, which can be changed any time during runtime. As I do not want a factory class nor a central management class I came up with that idea:
class MyClass
{
public:
void DoAnything() // Methode which should be act depending on default set.
{
// Do some stuff
if(getDefaultBehaviour())
{
// Do it this way...
}
else
{
// Do it that way...
}
}
static bool getDefaultBehaviour(bool bSetIt=false,bool bDefaultValue=false)
{
static bool bDefault=false;
if(bSetIt)
bDefault=bDefaultValue;
return bDefault;
}
};
It works, but it looks a little awkward. I wonder if there is a better way following the same intention.
In the case where I want to use it the software already created instances of that class during startup and delivered them to different parts of the code. Eventually the program gets the information how to treat the instances (for e.g. how or where to make themselves persistent). This decision should not only affect new created instances, it should affect the instances already created.
I'd advise to use a simple method to simulate a static data member, so the usage becomes more natural:
class MyClass
{
public:
// get a reference (!) to a static variable
static bool& DefaultBehaviour()
{
static bool b = false;
return b;
}
void DoAnything() // Methode which should be act depending on default set.
{
// Do some stuff
if(DefaultBehaviour())
{
// Do it this way...
}
else
{
// Do it that way...
}
}
};
where the user can change the default at any time with
MyClass::DefaultBehaviour() = true;
My thanks to Daniel Frey with his answer which I already marked as the best. I wanted to add my final solution which is based on the answer from Frey. The class is used by some c++ beginners. As I told them to use always getter and setter methods, the way described by Frey looks very complex to beginners ("uuuh, I can give a function a value?!?!"). So I wrote the class like followed:
class MyClass
{
public:
// get a reference (!) to a static variable
static bool& getDefaultBehaviour()
{
static bool b = false;
return b;
}
static void setDefaultBehaviour(bool value)
{
getDefaultBehaviour()=value;
}
void DoAnything() // Methode which should be act depending on default set.
{
// Do some stuff
if(getDefaultBehaviour())
{
// Do it this way...
}
else
{
// Do it that way...
}
}
};
for the user, I looks now like a usual getter and setter.

How can I keep track of (enumerate) all classes that implement an interface

I have a situation where I have an interface that defines how a certain class behaves in order to fill a certain role in my program, but at this point in time I'm not 100% sure how many classes I will write to fill that role. However, at the same time, I know that I want the user to be able to select, from a GUI combo/list box, which concrete class implementing the interface that they want to use to fill a certain role. I want the GUI to be able to enumerate all available classes, but I would prefer not to have to go back and change old code whenever I decide to implement a new class to fill that role (which may be months from now)
Some things I've considered:
using an enumeration
Pros:
I know how to do it
Cons
I will have to update update the enumeration when I add a new class
ugly to iterate through
using some kind of static list object in the interface, and adding a new element from within the definition file of the implementing class
Pros:
Wont have to change old code
Cons:
Not even sure if this is possible
Not sure what kind of information to store so that a factory method can choose the proper constructor ( maybe a map between a string and a function pointer that returns a pointer to an object of the interface )
I'm guessing this is a problem (or similar to a problem) that more experienced programmers have probably come across before (and often), and there is probably a common solution to this kind of problem, which is almost certainly better than anything I'm capable of coming up with. So, how do I do it?
(P.S. I searched, but all I found was this, and it's not the same: How do I enumerate all items that implement a generic interface?. It appears he already knows how to solve the problem I'm trying to figure out.)
Edit: I renamed the title to "How can I keep track of... " rather than just "How can I enumerate..." because the original question sounded like I was more interested in examining the runtime environment, where as what I'm really interested in is compile-time book-keeping.
Create a singleton where you can register your classes with a pointer to a creator function.
In the cpp files of the concrete classes you register each class.
Something like this:
class Interface;
typedef boost::function<Interface* ()> Creator;
class InterfaceRegistration
{
typedef map<string, Creator> CreatorMap;
public:
InterfaceRegistration& instance() {
static InterfaceRegistration interfaceRegistration;
return interfaceRegistration;
}
bool registerInterface( const string& name, Creator creator )
{
return (m_interfaces[name] = creator);
}
list<string> names() const
{
list<string> nameList;
transform(
m_interfaces.begin(), m_interfaces.end(),
back_inserter(nameList)
select1st<CreatorMap>::value_type>() );
}
Interface* create(cosnt string& name ) const
{
const CreatorMap::const_iterator it
= m_interfaces.find(name);
if( it!=m_interfaces.end() && (*it) )
{
return (*it)();
}
// throw exception ...
return 0;
}
private:
CreatorMap m_interfaces;
};
// in your concrete classes cpp files
namespace {
bool registerClassX = InterfaceRegistration::instance("ClassX", boost::lambda::new_ptr<ClassX>() );
}
ClassX::ClassX() : Interface()
{
//....
}
// in your concrete class Y cpp files
namespace {
bool registerClassY = InterfaceRegistration::instance("ClassY", boost::lambda::new_ptr<ClassY>() );
}
ClassY::ClassY() : Interface()
{
//....
}
I vaguely remember doing something similar to this many years ago. Your option (2) is pretty much what I did. In that case it was a std::map of std::string to std::typeinfo. In each, .cpp file I registered the class like this:
static dummy = registerClass (typeid (MyNewClass));
registerClass takes a type_info object and simply returns true. You have to initialize a variable to ensure that registerClass is called during startup time. Simply calling registerClass in the global namespace is an error. And making dummy static allow you to reuse the name across compilation units without a name collision.
I referred to this article to implement a self-registering class factory similar to the one described in TimW's answer, but it has the nice trick of using a templated factory proxy class to handle the object registration. Well worth a look :)
Self-Registering Objects in C++ -> http://www.ddj.com/184410633
Edit
Here's the test app I did (tidied up a little ;):
object_factory.h
#include <string>
#include <vector>
// Forward declare the base object class
class Object;
// Interface that the factory uses to communicate with the object proxies
class IObjectProxy {
public:
virtual Object* CreateObject() = 0;
virtual std::string GetObjectInfo() = 0;
};
// Object factory, retrieves object info from the global proxy objects
class ObjectFactory {
public:
static ObjectFactory& Instance() {
static ObjectFactory instance;
return instance;
}
// proxies add themselves to the factory here
void AddObject(IObjectProxy* object) {
objects_.push_back(object);
}
size_t NumberOfObjects() {
return objects_.size();
}
Object* CreateObject(size_t index) {
return objects_[index]->CreateObject();
}
std::string GetObjectInfo(size_t index) {
return objects_[index]->GetObjectInfo();
}
private:
std::vector<IObjectProxy*> objects_;
};
// This is the factory proxy template class
template<typename T>
class ObjectProxy : public IObjectProxy {
public:
ObjectProxy() {
ObjectFactory::Instance().AddObject(this);
}
Object* CreateObject() {
return new T;
}
virtual std::string GetObjectInfo() {
return T::TalkToMe();
};
};
objects.h
#include <iostream>
#include "object_factory.h"
// Base object class
class Object {
public:
virtual ~Object() {}
};
class ClassA : public Object {
public:
ClassA() { std::cout << "ClassA Constructor" << std::endl; }
~ClassA() { std::cout << "ClassA Destructor" << std::endl; }
static std::string TalkToMe() { return "This is ClassA"; }
};
class ClassB : public Object {
public:
ClassB() { std::cout << "ClassB Constructor" << std::endl; }
~ClassB() { std::cout << "ClassB Destructor" << std::endl; }
static std::string TalkToMe() { return "This is ClassB"; }
};
objects.cpp
#include "objects.h"
// Objects get registered here
ObjectProxy<ClassA> gClassAProxy;
ObjectProxy<ClassB> gClassBProxy;
main.cpp
#include "objects.h"
int main (int argc, char * const argv[]) {
ObjectFactory& factory = ObjectFactory::Instance();
for (int i = 0; i < factory.NumberOfObjects(); ++i) {
std::cout << factory.GetObjectInfo(i) << std::endl;
Object* object = factory.CreateObject(i);
delete object;
}
return 0;
}
output:
This is ClassA
ClassA Constructor
ClassA Destructor
This is ClassB
ClassB Constructor
ClassB Destructor
If you're on Windows, and using C++/CLI, this becomes fairly easy. The .NET framework provides this capability via reflection, and it works very cleanly in managed code.
In native C++, this gets a little bit trickier, as there's no simple way to query the library or application for runtime information. There are many frameworks that provide this (just look for IoC, DI, or plugin frameworks), but the simplest means of doing it yourself is to have some form of configuration which a factory method can use to register themselves, and return an implementation of your specific base class. You'd just need to implement loading a DLL, and registering the factory method - once you have that, it's fairly easy.
Something you can consider is an object counter. This way you don't need to change every place you allocate but just implementation definition. It's an alternative to the factory solution. Consider pros/cons.
An elegant way to do that is to use the CRTP : Curiously recurring template pattern.
The main example is such a counter :)
This way you just have to add in your concrete class implementation :
class X; // your interface
class MyConcreteX : public counter<X>
{
// whatever
};
Of course, it is not applicable if you use external implementations you do not master.
EDIT:
To handle the exact problem you need to have a counter that count only the first instance.
my 2 cents
There is no way to query the subclasses of a class in (native) C++.
How do you create the instances? Consider using a Factory Method allowing you to iterate over all subclasses you are working with. When you create an instance like this, it won't be possible to forget adding a new subclass later.