boost::signals2 and exception handling - c++

Is there some way to override the specific moment when a slot is called in boost::signals2 and perform some actions (logging, debugging, exception handling)?
I would like to catch exceptions at the moment of slot invocations, because signals/slots are where the execution path in my code crosses between various software components and each component is meant to be optional / can be disabled at run-time if it misbehaves. So when a slot invocation throws (might come from an external library, might just be std::bad_alloc), I would like to be notified about it -- and know which component was signaled into -- so I can kill that component.
I don't see how I can do it in a combiner because I don't have access to the slot or connection objects there? So I don't see a way to get any information. (Changing the return type on every slot is unfeasible.)
Is there some super easy way to do this that I've missed?
If not, how should I go about it?
Subclass something like slot_call_iterator (to wrap call in try/catch) and connection_body_base (to store information about what component it belongs to for example) and have boost use these? (How?)
Or subclass signals2::slot<...>, give it information about the owning component in the constructor and somehow overload the operator()(...)? (No idea about that either, seems way harder with all the template magic.)

To summarize the comments:
From Igor R.
Such a functionality doesn't seem to exist, but you can add a feature
request in the trac (or even provide a patch).
From integer (nice nickname):
Thank you for your comment. Yeah, I assumed it didn't exist, was just
wondering if there were a way to subclass or override publicly
exported boost classes to make my own, sort of. It can be intimidating
trying to do this blindly with boost code as I'd fear doing something
which might break or misuse internals.

Related

C++ Singleton Design pattern alternatives

I hate to beat a dead horse, that said, I've gone over so many conflicting articles over the past few days in regards to the use of the singleton pattern.
This question isn't be about which is the better choice in general, rather what makes sense for my use case.
The pet project I'm working on is a game. Some of the code that I'm currently working on, I'm leaning towards using a singleton pattern.
The use cases are as follows:
a globally accessible logger.
an OpenGL rendering manager.
file system access.
network access.
etc.
Now for clarification, more than a couple of the above require shared state between accesses. For instance, the logger is wrapping a logging library and requires a pointer to the output log, the network requires an established open connection, etc.
Now from what I can tell it's more suggested that singletons be avoided, so lets look at how we may do that. A lot of the articles simply say to create the instance at the top and pass it down as a parameter to anywhere that is needed. While I agree that this is technically doable, my question then becomes, how does one manage the potentially massive number of parameters? Well what comes to mind is wrapping the different instances in a sort of "context" object and passing that, then doing something like context->log("Hello World"). Now sure that isn't to bad, but what if you have a sort of framework like so:
game_loop(ctx)
->update_entities(ctx)
->on_preupdate(ctx)
->run_something(ctx)
->only use ctx->log() in some freak edge case in this function.
->on_update(ctx)
->whatever(ctx)
->ctx->networksend(stuff)
->update_physics(ctx)
->ctx->networksend(stuff)
//maybe ctx never uses log here.
You get the point... in some areas, some aspects of the "ctx" aren't ever used but you're still stuck passing it literally everywhere in case you may want to debug something down the line using logger, or maybe later in development, you actually want networking or whatever in that section of code.
I feel like the above example would much rather be suited to a globally accessible singleton, but I must admit, I'm coming from a C#/Java/JS background which may color my view. I want to adopt the mindset/best practices of a C++ programmer, yet like I said, I can't seem to find a straight answer. I also noticed that the articles that suggest just passing the "singleton" as a parameter only give very simplistic use cases that anyone would agree a parameter would be the better way to go.
In this game example, you probably wan't to access logging everywhere even if you don't plan on using it immediately. File system stuff may be all over but until you build out the project, it's really hard to say when/where it will be most useful.
So do I:
Stick with using singletons for these use cases regardless of how "evil/bad" people say it is.
Wrap everything in a context object, and pass it literally everywhere. (seems kinda gross IMO, but if that's the "more accepted/better" way of doing it, so be it.)
Something completely else. (Really lost as to what that might be.)
If option 1, from a performance standpoint, should I switch to using namespace functions, and hiding the "private" variables / functions in anonymous namespaces like most people do in C? (I'm guessing there will be a small boost in performance, but then I'll be stuck having to call an "init" and "destroy" method on a few of these rather than being able to just allow the constructor/destructor to do that for me, still might be worth while?)
Now I realize this may be a bit opinion based, but I'm hoping I can still get a relatively good answer when a more complicated/nested code base is in question.
Edit:
After much more deliberation I've decided to use the "Service Locator" pattern instead. To prevent a global/singleton of the Service Locator I'm making anything that may use the services inherit from a abstract base class that requires the Service Locator be passed when constructed.
I haven't implemented everything yet so I'm still unsure if I'll run into any problems with this approach, and would still love feedback on if this is a reasonable alternative to the singleton / global scope dilemma.
I had read that Service Locator is also somewhat of an anti-pattern, that said, many of the example I found implemented it with statics and/or as a singleton, perhaps using it as I've described removes the aspects that cause it to be an anti-pattern?
Whenever you think you want to use a Singleton, ask yourself the following question: Why is it that it must be ensured at all cost that there never exists more than one instance of this class at any point in time? Because the whole point of the Singleton pattern is to make sure that there can never be more than one instance of the Singleton. That's what the term "singleton" is all about: there only being one. That's why it's called the Singleton pattern. That's why the pattern calls for the constructor to be private. The point of the Singleton pattern is not and never was to give you a globally-accessible instance of something. The fact that there is a global access point to the sole instance is just a consequence of the Singleton pattern. It is not the objective the Singleton pattern is meant to achieve. If all you want is a globally accessible instance of something, then use a global variable. That's exactly what global variables are for…
The Singleton pattern is probably the one design pattern that's singularly more often misunderstood than not. Is it an intrinsic aspect of the very concept of a network connection that there can only ever be one network connection at a time, and the world would come to an end if that constraint was ever to be violated? If the answer is no, then there is no justification for a network connection to ever be modeled as a Singleton. But don't take my word for it, convince yourself by checking out page 127 of Design Patterns: Elements of Reusable Object-Oriented Software where the Singleton pattern was originally described…😉
Concerning your example: If you're ending up having to pass a massive number of parameters into some place then that first and foremost tells you one thing: there are too many responsibilities in that place. This fact is not changed by the use of Singletons. The use of Singletons simply obfuscates this fact because you're not forced to pass all stuff in through one door in the form of parameters but rather just access whatever you want directly all over the place. But you're still accessing these things. So the dependencies of your piece of code are the same. These dependencies are just not expressed explicitly anymore at some interface level but creep around in the mists. And you never know upfront what stuff a certain piece of code depends on until the moment your build breaks after trying to take away one thing that something else happened to depend upon. Note that this issue is not specific to the Singleton pattern. This is a concern with any kind of global entity in general…
So rather than ask the question of how to best pass a massive number of parameters, you should ask the question of why the hell does this one piece of code need access to that many things? For example, do you really need to explicitly pass the network connection to the game loop? Should the game loop not maybe just know the physics world object and that physics world object is at the moment of creation given some object that handles the network communication. And that object in turn is upon initialization told the network connection it is supposed to use? The log could just be a global variable (or is there really anything about the very idea of a log itself that prohibits there ever being more than one log?). Or maybe it would actually make sense for each thread to have its own log (could be a thread-local variable) so that you get a log from each thread in the order of the control flow that thread happened to take rather than some (at best) interleaved mess that would be the output from multiple threads for which you'd probably want to write some tool so that you'd at least have some hope of making sense of it at all…
Concerning performance, consider that, in a game, you'll typically have some parent objects that each manage collections of small child objects. Performance-critical stuff would generally be happening in places where something has to be done to all child objects in such a collection. The relative overhead of first getting to the parent object itself should generally be negligible…
PS: You might wanna have a look at the Entity Component System pattern…

Does it make sense to put everything in a subclass of QApplication?

In my plugin-based architecture, the plugins must have access to all core components of the application, e.g. the main window, the settingswidget, the settings, the tray icon and several global immutable variables.
Since the application is a global singleton it is straight forward to subclass it and make all those components members of the application. This way I can 1. easily access them from everywhere 2. I can facade their API for the plugins 3. it feels natural that the components are members of the "app".
However reading the lessons on SO about singletons and globals it feels like bad design, but otherwise I'd have to implement a core facade and pass it around, which feels like bad design as well and is definitively less straight forward.
Your description looks like a God object. That is indeed the sign of a potentially bad design.
Depending on what your plugins actually do, things like Observer pattern may be a solution. Instead of giving access to the resources, make your objects suscribe to a mediator and let it make the connections to the resources.
Take also a look to Inversion of control.
I think it's best to take the distinction between IS A and HAS A (inheritance vs. containment) seriously in this case.
A plug-in isn't a QApplication. It uses a QApplication. I don't see any reason to make it a subclass. Just give it a pointer or reference to QApplication.
This is one of the things the observer pattern does for you, subjects (QApplication) have references to their observers (Plugin). You also can use this in a symmetric way.
But using the observer pattern isn't always necessary. Main thing is your Plugins have a reference or pointer to the QApplication instance.
Not sure how it helps but it seems singleton classes are sometimes used to access them from the outside.
In KDE they seem to be refereed to as Conltroler, and seem to be used over Plugin-Boundarys. (KDE is QT based, so i assume a KDEPlugin is similar to a QT one.)
PS: This is in answer form, because i don't have "Comment everywhere".

The Obsever pattern (or something similar) using a global update() function in C++?

I am creating an MVC application in C++ and I want the lower level model classes to be able to update the GUI with simple text to display output to the reader. I don't want to have to pass around function or object pointers as it would get messy and I would have to pass them around all over the place. What I essentially want is the equivalent to 'cout' for a console GUI - some sort of global function that can be called to update the GUI from anywhere without having to know anything about the GUI.
I've mentioned the Observer pattern in the title because it sounds a lot like that - the GUI could subscribe to this global object or function in someway and listen for when it is called. However, I'm not specifically looking for a solution using Observer.
People have mentioned signals and slots to me but surely, unless global, you are still required to 'pass things around' to allow objects to emit the signals. Again, a global point of reference would be helpful.
How can I do this while ensuring that good design principles are adhered to?
Indeed, it seems appropriate to use Observer pattern here. However, I think you have a few mistakes here. You need to clearly define the roles of each participating party. I would suggest the following partition: the GUI is the observer (i.e., listener) and lower level objects are the ones signaling the changes to the listener. Upon initialization the lower-level module will register itself with the GUI (observer). Once the change occurs, the lower-level module will execute the public listening handler of the observer providing the needed data as input.
This will allow you to achieve your goal and no globals are involved in the scheme.
You can use stdout and stderr to do this. Just redirect output from them to your application. The simpliest possible solution - redirect application output to file and use tail -f redirected_output_file_name to see updates.
Or otherwise you can use log4cxx, you need to implement custom appender in this case.

Update GUI based on boolean

Trying to grey out certain buttons/text fields depending on the state of a boolean in my program. The boolean keeps track of if the connection to a subsystem is still up. Initializes to false until it connects, and then a watch dog keeps it updated from there on.
This may happen many times through the execution of the program, and thus I would like to make some sort of monitor that merely watches the state of the boolean and updates the GUI/button properties as appropriate.
My initial thought was to make some sort of event handler for this, but in my searches I found something called "properties" in C# that may make this even easier. Unfortunately I wasn't able to find a ton of information on this technique (initial thread here: How to trigger event when a variable's value is changed?)
So I have come to you folks with the hope that you may be able to give me an idea of the best way to do this.
Thanks,
EDIT:: Not sure if it matters, but the boolean is declared as an extern. This may make things easier, as I noticed in many cases the observer pattern is used when communicating between classes, which is not a concern in this problem.
C# properties just provide specialized syntax for getting/setting variables in an object. Since they are just specialized methods, you can really add whatever other functionality you want. From what you have described, I would probably recommend going with a listener... action listeners use a pattern called the "observer", which exactly fits what you're trying to do in this case. You can Google "observer pattern", and you'll get a lot more info on how to use it, and create your own variants, which you may or may not decide to do :)
Good luck!
Let me give you a simple example:
button1.IsEnabled = false;
To disable a button or a text field you just have to do that.

What's a pattern for getting two "deep" parts of a multi-threaded program talking to each other?

I have this general problem in design, refactoring or "triage":
I have an existing multi-threaded C++ application which searches for data using a number of plugin libraries. With the current search interface, a given plugin receives a search string and a pointer to a QList object. Running on a different thread, the plugin goes out and searches various data sources (locally and on the web) and adds the objects of interest to the list. When the plugin returns, the main program, still on the separate thread, adds this data to the local data store (with further processing), guarding this insertion point using a mutex. Thus each plugin can return data asynchronously.
The QT-base plugin library is based on message passing. There are a fair number of plugins which are already written and tested for the application and they work fairly well.
I would like to write some more plugins and leverage the existing application.
The problem is that the new plugins will need more information from the application. They will to need intermittent access to the local data store itself as they search. So to get this, they would need direct or indirect access both the hash array storing the data and the mutex which guards multiple access to the store. I assume the access would be encapsulated by adding an extra method in a "catalog" object.
I can see three ways to write these new plugins.
When loading a plugin, pass them
a pointer to my "catalog" at the
start. This becomes an extra,
"invisible" interface for the new
plugins. This seems quick, easy,
completely wrong according to OO but
I can't see what the future problems would be.
Add a method/message to the
existing interface so I have a
second function which could be
called for the new plugin libraries,
the message would pass a pointer to
the catalog to the plugins. This
would be easy for the plugins but it
would complicate my main code and
seems generally bad.
Redesign the plugin interface.
This seems "best" according to OO,
could have other added benefits but
would require all sorts of
rewriting.
So, my questions are
A. Can anyone tell me the concrete dangers of option 1?
B. Is there a known pattern that fits this kind of problem?
Edit1:
A typical function for calling the plugin routines looks like:
elsewhere(spec){
QList<CatItem> results;
plugins->getResult(spec, &results);
use_list(results);
}
...
void PluginHandler::getResults(QString* spec, QList<CatItem>* results)
{
if (id->count() == 0) return;
foreach(PluginInfo info, plugins) {
if (info.loaded)
info.obj->msg(MSG_GET_RESULTS, (void*) spec, (void*) results);
}
}
It's a repeated through-out the code. I'd rather extend it than break it.
Why is it "completely wrong according to OO"? If your plugin needs access to that object, and it doesn't violate any abstraction you want to preserve, it is the correct solution.
To me it seems like you blew your abstractions the moment you decided that your plugin needs access to the list itself. You just blew up your entire application's architecture. Are you sure you need access to the actual list itself? Why? What do you need from it? Can that information be provided in a more sensible way? One which doesn't 1) increase contention over a shared resource (and increase the risk of subtle multithreading bugs like race conditions and deadlocks), and 2) doesn't undermine the architecture of the rest of the app (which specifically preserves a separation between the list and its clients, to allow asynchronicity)
If you think it's bad OO, then it is because of what you're fundamentally trying to do (violate the basic architecture of your application), not how you're doing it.
Well, option 1 is option 3, in the end. You are redesigning your plugin API to receive extra data from the main app.
It's a simple redesign that, as long as the 'catalog' is well implemented and hide every implementation detail of your hash and mutex backing store, is not bad, and can serve the purpose well enough IMO.
Now if the catalog leaks implementation details then you would better use messages to query the store, receiving responses with the needed data.
Sorry, I just re-read your question 3 times and I think my answer may have been too simple.
Is your "Catalog" an independent object? If not, you could wrap it as it's own object. The Catalog should be completely safe (including threadsafe)--or better yet immutable.
With this done, it would be perfectly valid OO to pass your catalog to the new plugins. If you are worried about passing them through many layers, you can create a factory for the catalog.
Sorry if I'm still misunderstanding something, but I don't see anything wrong with this approach. If your catalog is an object outside your control, however, such as a database object or collection then you really HAVE to encapsulate it in something you can control with a nice, clean interface.
If your Catalog is used by many pieces across your program, you might look at a factory (which, at it's simplest degrades to a Singleton). Using a factory you should be able to summon your Catalog with a Catalog.getType("Clothes"); or whatever. That way you are giving out the same object to everyone who wants one without passing it around.
(this is very similar to a singleton, by the way, but coding it as a factory reminds you that there will almost certainly be more than one--also remember to allow a Catalog.setType("Clothes", ...); for testing.