I have recently been trying to remove the use of singletons and global variables from my project but I am having a hard time doing so. I have somewhat devised a better alternative to the singletons and global variables but I am not sure how to handle the data once my application is terminated.
My application needs access to a couple of things for most of the components to work properly; Some components need to access static std::vector<Foo*> foos;and others need to access static std::vector<Bob*> bobs; and some needs to access both. What I have done is created "Managers" for these vectors, a FooManager which gives access to the protected static vector to a class inheriting it and a BobManager which does the same thing for the other vector. By doing this limit the scope of these two objects. My problem is at process termination how and where do I deallocate the pointers in each vector? Multiple classes are now "Managers" of these objects. From the derived class? but what if I deallocate something while another class needs the original data?
Basically my question is how do I avoid deleting the pointers when I shouldn't be? unique_ptr? shared_ptr? Also any other implementation of this is welcome.
If you have the choice in your design, Idan's last paragraph is the way to go (included again):
If you still insist on avoiding the Singleton pattern, what I would
recommend is to make those vectors non-static again, create a single
instance of each manager once at your main function or any other
root-ish function, and pass them to any other object that needs them.
Yes, that's alot of work - but it lets you control when those
vectors(and the objects they point to) are created and destroyed. Or -
you could just use singletons.
Your Question:
Basically my question is how do I avoid deleting the pointers when I
shouldn't be? unique_ptr? shared_ptr? Also any other implementation of
this is welcome.
Reference Counting is one way to solve your problem. It keeps track of the number of things that are interested in a set of data. A quick way (with your current implementation) is to include a variable in the manager classes that keep track of how many instances there are. In the destructor decrement the counter. If the counter is 0 delete your vectors.
If I understood correctly, you have those two vectors that need to be accessed globally, and you used to have singletons to handle each. Now you want to remove those singletons, and instead make those vectors static members and have many instances of of the Manager classes?
Don't. Just... don't.
Global variables are a problem. There is a misconception that singletons are a kind of global variables and therefore are also a problem. They are not - singletons are the solution to the global variables problem. Removing the solution does not mean removing the problem - it just means you have a problem without a solution.
If you still insist on avoiding the Singleton pattern, what I would recommend is to make those vectors non-static again, create a single instance of each manager once at your main function or any other root-ish function, and pass them to any other object that needs them. Yes, that's alot of work - but it lets you control when those vectors(and the objects they point to) are created and destroyed. Or - you could just use singletons.
Related
I have a collection of objects, lets say QVector<ApplicationStates>, which registers the most important operations done in my software. Basically, this object is meant to process redo/undo operations.The application is built using a lot of delegated objects. Operations which have to be registered lie in a lot of these objects. As such, I am always passing my collection of objects, in each delegate under the form:
class AWidget : public QWidget{
AWidget(QVector<ApplicationStates>* states, QWidget* parent = nullptr);
...
It seems ugly to me. I think about two solutions:
Singleton;
Simply declare the QVector as a static global variable (I read that global variables are evil).
Does someone have a suggestion?
Thanks for your answers.
I get into a similar situation from time to time, and I have found simply wrapping your vector in a class called something like "ApplicationContext" then passing a shared pointer or reference to an instance of that around saves the day. It has many benefits:
You avoid the global / singleton, and you are free to in fact have several instances concurrently in the future
If you suddenly have more than just that vector of objects that you need to pass arround, simply extend your context class to add whatever you need
If your vector suddenly becomes a map or changes in other ways, you need not change any interfaces that pass it along such as the signals/slots. (You will need to change the implementation where the vector is used of course).
BONUS: The code becomes easily testable! You can now make test cases for this class.
This might not be the best solution in all cases, but I think it comes pretty close in this case!
I recently decided that a service locator would be an okay design pattern to access important managers for my game like a world manager (can spawn entities and keeps track of them) and a sound manager. However, I am not sure of the most appropriate way to have access to the service locator. I started by passing a pointer to the service locator I instanced in main, but this is becoming tedious, as I have found everything (projectiles, players, everything!) is needing it in it's arguments.
I am asking this here because I don't think that it is specific to games, but if I am wrong, just let me know.
Am I going about this pattern the wrong way?
Thanks for your time.
EDIT: Would a singleton solve this problem? They have a global point of access, but I don't think that it is the cleanest solution. Any ideas? Or would that be best?
This is a situation where using a global variable (or a Singleton) may be appropriate. You have to weigh the disadvantages of using a global variable / a singleton against the convenience of not having to pass a reference nearly everywhere. If you feel the disadvantages are unlikely to affect your design/code, then using a global variable can make your code much cleaner.
Some disadvantages of using a global variable are:
Managing the lifetime of your global can be more difficult. If you define multiple global variables in different translation units (cpp files), the order in which they are instantiated is unspecified, so they'd better not rely on each other during instantiation. One solution would be to store global pointers and instantiate the objects somewhere early in your program (e.g. in main), but then you have to make sure you don't create dangling pointers during the destruction phase of your program.
You may need to synchronize access to your global variable(s) in a multi-threaded context. With global variables it's harder to use per-thread objects (or proxies) to prevent having to synchronize access.
Additional disadvantages of a singleton can be:
Not being able to create copies of your class, e.g. for saving or undo.
Personally, I am in favour of using a single context object everywhere instead of using singletons. Have the context object provide you with functions to give you pointers/references or access to all the different services, managers, etc.
What is a good way to share an instance of an object between several classes in a class hierarchy? I have the following situation:
class texture_manager;
class world {
...
std::vector<object> objects_;
skybox skybox_;
}
I currently implemented texture_manager as a singleton, and clients call its instancing method from anywhere in the code. texture_manager needs to be used by objects in the objects_ vector, by skybox_, and possibly by other classes as well that may or may not be part of the world class.
As I am trying to limit the use of singletons in my code, do you recommend any alternatives to this approach? One solution that came to mind would be to pass a texture_manager reference as an argument to the constructors of all classes that need access to it. Thanks.
The general answer to that question is to use ::std::shared_ptr. Or if you don't have that, ::std::tr1::shared_ptr, or if you don't have that, ::boost::shared_ptr.
In your particular case, I would recommend one of a few different approaches:
One possibility is, of course, the shared_ptr approach. You basically pass around your pointer to everybody who needs the object, and it's automatically destroyed when none of them need it anymore. Though if your texture manager is going to end up with pointers to the objects pointing at it, you're creating a reference cycle, and that will have to be handled very carefully.
Another possibility is just to declare it as a local variable in main and pass it as a pointer or reference to everybody who needs it. It won't be going away until your program is finished that way, and you shouldn't have to worry about managing the lifetime. A bare pointer or reference is just fine in this case.
A third possibility is one of the sort of vaguely acceptable uses of something sort of like a singleton. And this deserves a detailed explanation.
You make a singleton who's only job is to hand out useful pointers to things. A key feature it has is the ability to tell it what thing to hand out a pointer to. It's kind of like a global configurable factory.
This allows you to escape from the huge testing issues you create with a singleton in general. Just tell it to hand out a pointer to a stub object when it comes time to test things.
It also allows you to escape from the access control/security issue (yes, they create security issues as well) that a singleton represents for the same reason. You can temporarily tell it to pass out a pointer to an object that doesn't allow access to things that the section of code you're about to execute doesn't need access to. This idea is generally referred to as the principle of least authority.
The main reason to use this is that it saves you the problem of figuring out who needs your pointer and handing it to them. This is also the main reason not to use it, thinking that through is good for you. You also introduce the possibility that two things that expected to get the same pointer to a texture manager actually get pointers to a different texture manager because of a control flow you didn't anticipate, which is basically the result of the sloppy thinking that caused you to use the Singleton in the first place. Lastly, Singletons are so awful, that even this more benign use of them makes me itchy.
Personally, in your case, I would recommend approach #2, just creating it on the stack in main and passing in a pointer to wherever it's needed. It will make you think more carefully about the structure of your program, and this sort of object should probably live for your entire program's lifetime anyway.
In a C++ multi-threaded application with many classes, i am trying to find out what are the methods to define a global variable
C style, define it as global in any one source file, define it as extern in a header which is included in the classes that access this variable.
Write a Singleton class, which contains these global variables and exposes set/get methods to write to the variable.
By second method one can control multi-threaded access via locks in a centralized manner rather than the first approach.
Are there more and better ways?
First of all try to avoid global variables as much as you can. If you just need to do it (by example this is the case with cin, cout and cerr) your second method is definitely the best (and more natural) way of doing it.
If the scope of your "global variable" can be narrowed down (which is typically the case - how many variables are truly global?) then you can make it a private static class member in the appropriate owning class. If your other classes need to see it (or less likely, update it), provide get/put accessors.
I would definitely go with the Singleton class. It's the best way to handle "global" variables in a multithreaded OOP environment.
If you must use a global variable (and why are you using one?) I recommend the second way you described. The first way is the way you can run into all kinds of namespace problems.
This probleam can be solved with an alternatieve method very easily.
C++ resolves this problem very easily by its new operator :: called scope resolution operator. The syntax is as follows
:: variable-name;
This operator allows access the global version of a vriable.
One tends to prefer the second method, because it seems to give you a better control but it may not turn out very useful in some scenarios.
First, In my understanding of philosophy of OOP, I do not consider objects as collections of bunch of data, but entities in terms of which, you can represent real world problems. So I do not consider it a good idea to to have a class to store random data. Especially when the data members are largely unrelated.
Second, If you are thinking of having a central control eg. having a single mutex to access all the data members, this is not going to work out very well for unrelated data members. You are going to block a lot of threads unnecessarily while the data they want is not exactly the one which is being currently protected by the lock.
So it may seem strange, but I would prefer the first method.
It depends on the problem at hand.
C-style globals have the advantage of simplicity, no need for Singleton::instance() call. However, Singleton::instance() allows you to initialize your global state on the first call.
To get the best of both worlds use C-style globals initialized using Schwarz Counter method. http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter
You can define a value object that wraps a single implementation with the handle/body idiom.
Also review "Modern C++ Design" by Alexandrescu for discussion about the difficulties of implementing singleton in MT environments and how to go about addressing them.
Not to kick a dead horse but, as mentioned, avoiding globals is the best solution. Some reasons are listed here. If a global variable is a must you might want to consider providing a function to access it from to avoid the so called 'global initialization fiasco'.
I have read multiple articles about why singletons are bad.
I know it has few uses like logging but what about initalizing and deinitializing.
Are there any problems doing that?
I have a scripting engine that I need to bind on startup to a library.
Libraries don't have main() so what should I use?
Regular functions or a Singleton.
Can this object be copied somehow:
class
{
public:
static void initialize();
static void deinitialize();
} bootstrap;
If not why do people hide the copy ctor, assignment operator and the ctor?
Libraries in C++ have a much simpler way to perform initialization and cleanup. It's the exact same way you'd do it for anything else. RAII.
Wrap everything that needs to be initialized in a class, and perform its initialization in the constructor. Voila, problems solved.
All the usual problems with singletons still apply:
You are going to need more than one instance, even if you hadn't planned for it. If nothing else, you'll want it when unit-testing. Each test should initialize the library from scratch so that it runs in a clean environment. That's hard to do with a singleton approach.
You're screwed as soon as these singletons start referencing each others. Because the actual initialization order isn't visible, you quickly end up with a bunch of circular references resulting in accessing uninitialized singletons or stack overflows or deadlocks or other fun errors which could have been caught at compile-time if you hadn't been obsessed with making everything global.
Multithreading. It's usually a bad idea to force all threads to share the same instance of a class, becaus it forces that class to lock and synchronize everything, which costs a lot of performance, and may lead to deadlocks.
Spaghetti code. You're hiding your code's dependencies every time you use a singleton or a global. It is no longer clear which objects a function depends on, because not all of them are visible as parameters. And because you don't need to add them as parameters, you easily end up adding far more dependencies than necessary. Which is why singletons are almost impossible to remove once you have them.
A singleton's purpose is to have only ONE instance of a certain class in your system.
The C'tor, D'tor and CC'tor are hidden, in order to have a single access point for receiving the only existing instance.
Usually the instance is static (could be allocated on the heap too) and private, and there's a static method (usually called GetInstance) which returns a reference to this instance.
The question you should ask yourself when deciding whether to have a singleton is : Do I really need to enforce having one object of this class?
There's also the inheritance problem - it can make things complicated if you are planning to inherit from a singleton.
Another problem is How to kill a singleton (the web is filled with articles about this issue)
In some cases it's better to have your private data held statically rather than having a singleton, all depends on the domain.
Note though, that if you're multi-threaded, static variables can give you a pain in the XXX...
So you should analyse your problem carefully before deciding on the design pattern you're going to use...
In your case, I don't think you need a singleton because you want the libraries to be initialized at the beginning, but it has nothing to do with enforcing having only one instance of your class. You could just hold a static flag (static bool Initialized) if all you want is to ensure initializing it only once.
Calling a method once is not reason enough to have a singleton.
It's a good practice to provide an interface for your libraries so that multiple modules (or threads) can use them simultaneously. If you really need to run some code when modules are loaded then use singletons to init parts that must be init once.
count the number of singletons in your design, and call this number 's'
count the number of threads in your design, and call this number 't'
now, raise t to the s-th power; this is roughly the number of hairs you are likely to lose while debugging the resulting code.
(I personally have run afoul of code that has over 50 singletons with 10 different threads all racing to get to .getInstance() first)