In my code I'm implementing so many different classes that need to be initialized once the program's process is activated.
I am currently initiating manually each class, but they are so many, I thought that I could inherit from some class and each object created would be saved in a vector and could initalize the class from the object (base class) created, but I only need to initalize the class once, and even though I can set a flag for that, I dont think its a good solution.
Other solution that I thought is implement a kind of initializer on each class (static variable) that I have to initalize, same implementation, save the init object per class in a vector, and then init all the classes from the initializer class, but I have to pass to that object a lot of parametres and even functions.
so is a good solution but a bad implementing, think so.
so Do you know for some good pattern to initialize classes?
EDIT: EXAMPLE:
With Android and OpenGL, each time the app is not OnResume(), the Opengl context is destroyed, and OnResume() the context is recreated, and for any object that I need to render, I have a class for example 'Square class' that draws squares, and for each square object I have static variables in the 'Square class', that each square has access to be rendered properly with opengl, like buffers or shaders, etc, so any time the context is recreated, I need to reinitialize the class static variables in order that the object be rendered.
One standard pattern for initialisation in C++ is the nifty-counter pattern. See http://www.petebecker.com/js/js199905.html. To summarise, in your header file you define an object with a constructor, so this constructor will be executed once for each .cpp that includes the header file. This constructor increments a global shared counter. If the counter goes from 0 to 1 you run initialisation code. Similarly, the destructor decrements the counter, and de-initialises or destroys stuff when it goes from 1 to 0.
This works well with the only C++ guarantee about order of initialisation, which is that, within the same file, objects are constructed and initialised from top to bottom. If people have multiple .cpps which reference each other via header files, the first thing that gets initialised will be defined in a header that does not include anything else that needs initialisation first, which should be the something that does not depend on anything else.
Maybe I get this totally wrong, but at least in the Java world, one way of solving this topic is by using dependency injection via frameworks that take care of init'ting your objects, based on configuration information that you have to provide.
Meaning: you completely separate your actual "business logic" and the task of "establishing all the required objects". You don't do "new" any more in your code; all the important objects are created for you "by magic".
One example of such a framework for C++ would be fruit, which is actually inspired by Google's guice thing for java.
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 have a simple question. I have a class that does not have any variables, it is just a class that has a lot of void functions (that display things, etc.). When I create an object of that class, would it be better/more efficient to pass that one object through all my functions as the program progresses, or to just recreate it every time the program goes into a new function? Keeping in mind, that the object has no variables that need to be kept. Thanks in advance for any help.
It makes much more sense that the class only has static functions and no instance is necessary at all. You have no state anyway...
For performance concerns, there is almost no difference. Passing an object as argument will cost you a (very tiny) bit at runtime. Recreating object will not (assuming compiler optimizations).
However, if you ever have plans to introduce some state (fields), or have two implementations for those void methods, you should pass an object, as it greatly reduces refactoring cost.
Summarize: if your class is something like Math where methods stateless by nature, stick with #Amit answer and make it static. Otherwise, if your class is something like Canvas or Windows and you have thoughts on implementing it another way later, better pass it by reference so you can replace it with abstract interface and supply actual implementation.
if the functions in the otherwise empty class never change... consider making them static. or put them in a namespace instead of a class.
on the other hand... if the functions are set once at runtime, like say you pick which display functions to use based on os, then store them in a global. or singleton.
on the gripping hand... if the functions are different for different parts of the greater code... then yes you'll have to somehow deliver it to whatever functions need it. whether you should create once and pass many times - or pass never and create as needed, really depends on the specifics of your application. sorry, there's no universal answer here.
I have a question on where to create, own and destroy data.
The data itself are large tables of numbers, either randomly generated or read from the hard drive. This data is then subject to analysis, and depending on what exactly is analyzed, I have made a few wrapper like structures, which encapsulated the desired functionality. Since the wrapper can be switched in later stages, I decided against creating/reading the data inside the wrapper constructors, and just handle them in the "main" function. The wrappers then only see pointers of the data.
First of, is this common/ a good idea, or should a wrapper always own its own copy of the data it wraps around?
Well, next I made a "menu" class to better navigate through data creation/analysis choices etc, and the easiest would be to make the data part of the menu class. This doesn't feel good though, so where should I put it? Should it stay in the main class?
I hope this is understandable. If not, I can try to give a better outline of what is happening.
Thank you for reading.
You could create a data class, and wrap other classes around it. An object of the data class probably should be global or defined inside main. OTher than that - your idea seems good. WIth a data class defined, you could also pass a pointer/reference to the menu, so you wouldn't have the problem with that. Note that a menu can also be a wrapper if you wish.
It's generally a better idea to keep the details of data in a specific wrapper class (I think you mean derived class?). Your wrapper classes should be derived from an interface or abstract type. You can construct wrapper-class factories in main(), and pass the factories around to constructors (constructors of the classes that are instantiated in main()). Later when the data-specific wrapper needs to be switched on or created, invoke the factory method. The factories can own the pointers, by which I mean they call new() and delete(). Try looking up SOLID principles and see how they guide you.
I need suggestions on how to solve the type of problems described below. I'm fairly new at C++ and OO-design.
I've learnt:
Pointers shall be avoided when ever they can be replaced by references.
Objects shall have no knowledge of objects that they don't need to know about.
But when creating objects having references to other objects we must pass these references as input arguments to the constructor. Thus we need to know about objects we should not not know anything about.
But look at the following example:
Suppose I have a object "Menu" that needs to have it's own timer object "Timer". I'd like to implement this association as a reference.
The object MenuHandler aggregates a lot of Menu objects but shall not have any knowledge about Timer objects. But when the MenuHandler creates a Menu object it must pass a Timer reference argument to the constructor. Thus, ****MenuHandler** must know about **Timer****.
Any suggestions on how to treat these kind of problems?
I'd hesitate to bless your choice of words when it comes to the two numbered points. They're a sign you're on the right way learning C++, but they might be misleading to other novices. When I take a look at your concrete examples, this becomes more obvious.
A MenuHandler should not create menus. The content of menus is determined by by the application, so the application object (or the Controller part, if you've implemented Model-View-Controller) should create menus. The MenuHander merely takes ownership of menus created elsewhere.
Also, it may make sense to give each menu its own timer. That means the relation can be described as "Has a"; the menu has a timer. The relationship usually implmented by references can be described as "Knows a" (the inheritance relationship is usally called "Is a"). If each Menu object has a Timer, it can be a member, and initialized by the Menu constructor(s). The Timer object internally may obtain a reference to the system clock in its constructor, but that's not your concern.
Why not simply make the Timer object a member (by value) of the Menu class?
I find that I produce better (more maintainable, faster, etc) code and that I'm more productive using references in C++ than I would be solving the same problem with pointers... I think the traditional answer to your example would be to have a factory object that creates menus. In this way, the MenuHandler doesn't need to know about the Timer class.
The MenuHandler creates a Timer object, passes it into the Menu constructor, and forgets about it. That seems entirely reasonable.
If the MenuHandler unnecessarily kept a reference to the Timer, that would be against the advice point #2.
In a more general case where you need to provide a class to another class in order to do some kind of callback, you avoid mutual dependency (both know each other) by using an interface.
Class A derives from the interface. Class B accepts the interface as paramater in the constructor and calls the virtual function from that interface when needed.
Also check the observer design pattern.
For #1 Be very careful with the lifetime of your objects. References are no that suitable to handle dynamic graph of objets ( like your menu, menuhandler, timer, etc... ). What if you want to change the timer object later ?
It's not a good idea to have references as members in a class if the lifetime of referenced objects is not really known.
Avoiding pointer does not mean using references everywhere, you should have a look at smart pointers which will be more suitable for what you want to do.
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)