What is the best way to represent a single global class instance? - c++

I have a project, which has its own filesystem. The class basically looks like this:
class ResourceManager {
public:
std::string readFile(std::string const&);
private:
std::vector<std::string> root;
};
This class is used everywhere in the project. So it's global and have a single instance. My current solution is that I create an instance in the main function and then pass it to all of my classes (they store a reference). I'm absolutely fine with this approach, besides that i need to pass the instance to regular functions, but I'm curious if it's possible to archive a better result.
A simple way of making a filesystem is just to have static functions, because you don't really need any variables to store. But in my case I have a variable called root, which stores search directories so that I can do something like this:
rm.addResourceRoot(ResourceType::images, "path/to/directory");
I can have a static variable ResourceManager* instance and method ResourceManager& getRm() { return *instance; } inside a class, but that approach feels kind of weird and probably isn't a "best practice". Probably outside-of-class functions like this will help to make it look better, but I'm still hesitating.
std::string readFile(std::string const& path) {
return ResourceManager::getRm().readFile(path);
}
I can use singleton pattern, but everyone convinces me not to use it, because it's an anti-pattern and not good solution at all. This confuses me in some way so it would be great if anyone could explain the reasons to me.
In my opinion, the ideal access should look like this:
ResourceManager::readFile("path/to/file");
So what is the best way to represent such entities in a project?

Related

C++ : Is it bad practice to use a static container in a class to contain pointers to all its objects for ease of access?

I would like to know if it's bad practice to have a static container in a class to store all the pointers to the class' objects so they can all be easily accessed by the base classes of the program. This is for a game and I saw it on sdltutorials dot com, and I find it very useful. It would allow me to have a very neat structure for my game and I don't really see a downside doing this, but I know I have to be careful with "global" access and maybe there's a negative effect I'm not seeing right now.
Here is the context/example. The game has a base class with basic methods such as Loop(), Render(), PlayAudio(), CleanMemory(). The idea is to have individual objects to have the same methods being executed inside the base method. Example in pseudocode:
Game::Render() {
for (iterate all enemies in static container) {
current_enemy::Render();
}
}
To be sure, the static member inside the class would look like this:
static std::vector<Enemy*> EnemyList;
So this way, when your game is executing the base Render() method, for example, you can iterate all the enemies in the enemies' class static container and execute all their individual Render() methods, then do the same for environment objects, then for the player, etc.
I would just like to make sure I'm aware of any downside/complication/limitation I might encounter if I choose this method to build my game, because I don't see any right now but I know a have to be careful with static and global stuff.
Thanks very much for your time.
It is certainly convenient, however a static variable or a Singleton are nothing more than global variables; and having global variables comes with drawbacks:
the dependencies of a function become unclear: which global does it rely upon ?
the re-entrancy of a function is compromised: what if current_enemy.render() accidentally calls Game::Render() ? it's an infinite recursion!
the thread-safety of a function is compromised, unless proper synchronization takes place, in which case the serialized access to the global variable bog down the performance of your concurrent code (because of Amdahl's Law)
It might seem painful and pointless to explicitly pass a reference to an instance of Game wherever you need to, however it leaves a clear path of dependencies that can be followed and as the software grows you will appreciate explicitness.
And there is, of course, much to be said about transforming the program to have two instances of Game. While it might seem incongruous in this precise situation, in general it is wise not to assume that it will never be necessary in the future, for we are no oracles.
Different people may have different opinions about this. I can give you some advice on how to store your static objects in a better way.
Use the singleton pattern for a class which stores your objects:
class ObjectManager
{
private:
std::vector<Enemy*> enemies_;
std::vector<Friend*> friends_;
...
public:
void add(Enemy* e) { enemies_.push_back(e); }
...
const std::vector<Enemy*> enemies() const { return enmies_; }
...
private:
static ObjectManager* instance_;
public:
static ObjectManager* Get() { return instance_; }
static void Initialize() { instance_ = new ObjectManager(); }
}
You can access it like that (example with C++11 ranged-based for):
void Game::Render() {
for(auto e : ObjectManager::Get()->enemies()) {
e->Render();
}
}
This is especially convenient for subclasses which want to access information about the world. Normally you would have to give a pointer to ObjectManager to everyone. But if you have only one ObjectManager anyway the singleton pattern may remove clutter from your code.
Don't forget to create the singleton at the beginning of your program by calling ObjectManager::Initialize();.
I would not suggest doing this the way you are. At this point you may as well have a bare global variable in a namespace, it is the same thing you are doing right now.
I also do not suggest using singletons.
When should the Singleton pattern NOT be used? (Besides the obvious)
The best way to approach things is to do good old parameter passing (dependency injection) wherever possible. With careful design this is feasible system wide, and it avoids all the problems you have with globally accessible resources.
When you don't have the luxury of designing your system in such a way, and you are working within existing code that already has quite a bit of trouble with singleton dependence, or loss of locality between resources several levels removed from where they are needed (and you cannot afford to modify the interfaces to cascade dependencies downward) this may not be useful advice.
A middle-ground between bare global and singleton is the service-locator. Many people still consider service-locator an anti-pattern, but most people also agree that it is less bad than the singleton since it offers a certain level of abstraction and decouples creation from supplying the object which means you can offer up a derived class easily if your design or environment changes.
Here is a description of the pattern:
http://gameprogrammingpatterns.com/service-locator.html
And here is a discussion about the singleton vs service-locator.
If Singletons are bad then why is a Service Container good?.
I like the highest voted (but not accepted) answer best.

Class interface query

I've been wondering about a design that I've been using for quite some time for my game engine and games. Let's say we have an Object class
class Object
{
public:
const std::string& getName() { return m_name; }
private:
std::string m_name;
}
Then, I have a class called ObjectManager, which holds an instance of Object. Now, I've been wondering if I should keep that instance private in ObjectManager and duplicate code so that it could call getName(), or make Object public which defeats the concept of encapsulation. Which design do you guys think is better?
Thanks for any help!
If your class contains an object that is usable by others, expose it. Encapsulation is meant to hide variables needed to do something. Certain data members don't fall into this.
Example:
Person tom;
tom.getEyes().getColor();
tom.getMouth().eat(tomato);
tom.legs().walk();
Person could hide everything but it would be cumbersome:
tom.getEyesColor(); // accessor for every eye feature
tom.eat(tomato);
tom.walkAndEat(); // every possible combination of actions
Further example:
grid.row(3).col(5).setText("hello");
Here a column class could expose many methods without the grid class having to be touched. This is the beauty of object oriented programming.
If you named your class ObjectManager i get the feeling it is managing Object instances for others so you ought to expose it. The other idea to use inheritance is also valid:
class ObjectManager : public Object
{
};
If you want to restrict the interface to methods only then keep the object private and use an accessor method that returns a const reference (and non const if needed) to the private object.
Also, inheritance is a good option if applicable.
It depends on what you're doing. If I understand your question correctly, I'd personally lean more towards making the Object a private member of ObjectManager and adding a function to ObjectManager to act as a proxy for Object::getName(). (Is this your question?) However if you're just wrapping particularly thinly and are not trying to do something particularly technical or what have you, I might be tempted to answer otherwise. It depends, but more than likely, go ahead and make it private and add the extra function. Note that this answer is based on the assumption that you're going to make heavy use out of inheritance here.
It really depends on the situation (Sorry for the non-answer!). If you do want to support strong encapsulation, you would probably want ObjectManager to look something like this:
public class ObjectManager
{
private:
Object obj;
public:
string GetNameOfInnerObject();
}
As you can see I changed the method header to be descriptive with respect to ObjectManager. This type of method naming can come in handy to abstract an object's more complex interactions within itself away.
Edit: It might help if you tell us what ObjectManager is supposed to do. Does it have any methods that don't correspond directly to your inner object?

STL Metaprogramming - which types of my template class have been created at compile time?

First the apologies, i'm not sure if my question title even accuratly explains what I'm asking - I've had a look through google, but i'm not sure which terms I need in my search query, so the answer may be out there (or even on StackOverflow) already.
I have a templated class, which basically looks like the following - it uses the Singleton pattern, hence everything is static, I'm not looking for comments on why I'm storing the keys in a set and using strings etc, unless it actually provides a solution. There's a bit more to the class, but that isn't relevant to the question.
template<typename T>
class MyClass
{
private:
//Constructor and other bits and peices you don't need to know about
static std::set<std::string> StoredKeys;
public:
static bool GetValue(T &Value, std::string &Key)
{
//implementation
}
static SetValue(const T Value, std::string &Key)
{
//implementation
StoredKeys.Insert(Key);
}
static KeyList GetKeys()
{
return KeyList(StoredKeys);
}
};
Later on in some other part of the application I want to get all the Keys for all of the values - regardless of type.
Whilst I am fairly confident that at the moment only 3 or 4 types are being used with the class so I could write something like:
KeyList Keys = MyClass<bool>::GetKeys();
Keys += MyClass<double>::GetKeys();
Keys += MyClass<char>::GetKeys();
This will need to be updated each time a new type is used. It also has the downside of instantiating the class if it's not used anywhere.
I think (again I could be wrong) that metaprogramming is the answer here, some sort of macro maybe?
We're using boost, so I'm guessing the MPL library could be useful here?
This aspect of STL is a bit new to me, so I'm happy to read up and learn as much as I need, just as soon as I know exactly what it is I need to learn to engineer a solution.
Move StoredKeys into a non-template base class class MyClassBase, or add an AllStoredKeys static member to a non-template base class.
Alternatively, create a static init method called from SetValue that adds a pointer to StoredKeys to a static list.
There's no magic. If you need to enumerate all the types used to instantiate MyClass in your program, then you have to enumerate them explicitly, somewhere. somehow. And you have to manually update the list whenever it changes.
With template metaprogramming, the number of places you need to update manually can be reduced down to one, but you do need that one place.
Fortunately, in this particular problem you don't need to enumerate all the types. You just need to store all keys in one set, as opposed to splitting them between several sets. You may create a common non-template base to MyClass and add static std::set<std::string> StoredKeys there (or perhaps make it a multiset if there's a possibility of identical keys in different type-specific sets).
The first answere: Its not possible!
Template classes dont actually have a "generics" in common (like in java) but a separate classes which dont have anything to do with eachother.
The second answere: Theres a workaround. One can define a base class MyClassBase which defines properties shared by all templated subclasses. The problem is that you have a singleton pattern here which might makes the situation a bit more compilcated. I think a solution might look like this:
class MyClassBase {
static std::vector<MyClassBase*> childs;
static KeyList getAllKeys(){
//iterate over childs here and call ->GetKeys
}
virtual KeyList GetKeys() = 0;
template<typename T>
static T* instance() {
T* instance = MyClass<T>::instance();
if(std::find(childs.begin(), childs.end(), instance) != childs.end()){
childs.push_back(instance);
}
return instance;
}
};
Please forgive me any syntactic errors; I just typed that in the Stackoverflow editor, but i think it should make my point clear.
Edit:
I just saw that I named the singleton method of the subclasses also instance(). This will probably not work. Give it some other name like privateInstance() or so. Then you must change T* instance = MyClass<T>::instance(); to T* instance = MyClass<T>::privateInstance();

How to design an interface for a simple conversion routine?

I have a simple regex conversion method that I use to do some minor processing to HTML passed in as a std::string. The method looks like:
std::string ParseQuotedPrintableHtml( std::string const& html );
I want to design this method into some sort of small library that can be used across my whole code base. Since it's just a single function, one might be tempted to just create a Utility class (or namespace) and stuff the function in there. I feel this is a bit of a naive design. Any suggestions on a good rule of thumb as to how to design functionality like this into a centralized and accessible location?
EDIT
I should also mention that there are several "helper" functions that this function calls (I also created these, and they are only useful to and used by this method). Ideally these would be "private" in a class, but if I keep this as a global function, those implementation methods will also be accessible in the global namespace (or whichever namespace I place them in).
I guess due to this, it's best to create a utility class maybe?
class QuotedPrintableHtml
{
private:
void HelperMethod1() const;
void HelperMethod2() const;
std::string html_;
public:
QuotedPrintableHtml( std::string const& html ) : html_(html) {}
std::string Parse() const;
};
Perhaps something like this?
I wouldn't advise creating a class: the utility functions don't share some state so I would just create a namespace like Utilities to collect those free functions. You can put all the helper functions you don't want to share in an anonymous namespace inside your cpp file.

Best way to take a snapshot of an object to a file

What's the best way to output the public contents of an object to a human-readable file? I'm looking for a way to do this that would not require me to know of all the members of the class, but rather use the compiler to tell me what members exist, and what their names are. There have to be macros or something like that, right?
Contrived example:
class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
int otherStuff;
};
Container myCollection;
I would like to be able to do something to see output along the lines of "myCollection: stuff = value, otherStuff = value".
But then if another member is added to Container,
class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
string evenMoreStuff;
int otherStuff;
};
Container myCollection;
This time, the output of this snapshot would be "myCollection: stuff = value, evenMoreStuff=value, otherStuff = value"
Is there a macro that would help me accomplish this? Is this even possible? (Also, I can't modify the Container class.)
Another note: I'm most interested about a potential macros in VS, but other solutions are welcome too.
What you're looking for is "[reflection](http://en.wikipedia.org/wiki/Reflection_(computer_science)#C.2B.2B)".
I found two promising links with a Google search for "C++ reflection":
http://www.garret.ru/cppreflection/docs/reflect.html
http://seal-reflex.web.cern.ch/seal-reflex/index.html
Boost has a serialization library that can serialize into text files. You will, however, not be able to get around with now knowing what members the class contains. You would need reflection, which C++ does not have.
Take a look at this library .
What you need is object serialization or object marshalling. A recurrent thema in stackoverflow.
I'd highly recommend taking a look at Google's Protocol Buffers.
There's unfortunately no macro that can do this for you. What you're looking for is a reflective type library. These can vary from fairly simple to home-rolled monstrosities that have no place in a work environment.
There's no real simple way of doing this, and though you may be tempted to simply dump the memory at an address like so:
char *buffer = new char[sizeof(Container)];
memcpy(buffer, containerInstance, sizeof(Container));
I'd really suggest against it unless all you have are simple types.
If you want something really simple but not complete, I'd suggest writing your own
printOn(ostream &) member method.
XDR is one way to do this in a platform independent way.