static protected resource shared through inheritance - c++

In an attempt to replace the singleton pattern and a general "Resource Manager", I came with a solution. Making a resource static and protected. That resource is shared between all children from the inherited class. It works, but I wasn't sure if it's a good way to proceed.
Here's a bit of code to express what I'm doing(the resource here is the sf::Texture):
class Foo {
public:
Foo() {
if(m_texture == nullptr) {
//Création et chargement de la texture
m_texture = std::unique_ptr<sf::Texture>(new sf::Texture());
m_texture->loadFromFile("...");
}
}
void draw(sf::RenderWindow& window) = 0;
protected:
static std::unique_ptr<sf::Texture> m_texture = nullptr;
};
class Bar : public Foo {
public:
Bar()
: m_sprite(*m_texture) {}
void draw(sf::RenderWindow& window) {
window.draw(m_sprite);
}
private:
sf::Sprite m_sprite;
};
That way my resources is shared through all children, and is only initialized once.
Is it a good solution to replace a singleton or a Resource Manager that I would carry everywhere through reference.
Thank you!

Fundamentally what you are tying to do is correct, a static member will be shared (ie be exactly the same) among all the inherited class, this way you only need a single instance which can save you a ton of memory but heres a couple issues ... Im assuming you are using g++.
You can't initialize non-const member within a class declaration so this.
static std::unique_ptr<sf::Texture> m_texture = nullptr;
would produce this:
error: ISO C++ forbids in-class initialization of non-const static member
you have to initialize it within the source file of your class, but outside the class.
std::unique_ptr<sf::Texture> Foo::m_texture = nullptr;
Second it isn't save to access member fields directly, always use setters and getters, even within the class functions, this makes the code much more maintainable. As such you can have a static function called getTexture
static std::unique_ptr<sf::Texture> getTexture() {
if(m_texture == nullptr) {
//Création et chargement de la texture
m_texture = std::unique_ptr<sf::Texture>(new sf::Texture());
m_texture->loadFromFile("...");
}
return m_texture;
}
while its true that the if statement and function call do add come overhead, this is much more maintainable and safer, and it load the texture at the last minute when its truly needed.
Back to your question, the Singleton design pattern is quite simple and mostly used to save memory since only a single instance of the object is ever created :) Resource managers are a whole different beast their goal is to centralize all the actions that are required loading and managing resources, combining the two you would initialize a single instance of a resource manager, then access it though a static member field, having all the objects make requests for resources, this could be good or bad, depending on what you are trying to achieve.
Software design is hard. The best advice I can give is this, when designing a system ask yourself this, "how many lines of code would I have to write to introduce another similar component" your goal should be to minimize this as much as possible, ie reuse as much as possible what you have already created.
The best programmers are the laziest :) and no I don't mean copy/paste, that should be banned.

The design looks suspicious. I don't see any advantage of using this over the more widely used Singleton pattern (with a function local static instance). You're probably best off initializing the m_texture object with a default Texture at the point of definition (and not within Foo's ctor):
static std::unique_ptr<sf::Texture> m_texture( new sf::Texture() );
Data members are ideally suited for derived classes. Base classes are typically to define interfaces.
I'd suggest that you keep your resource manager class (Foo) separate and instead of inheriting from it, call appropriate member functions to get to the Texture object.

Related

Should I use static classes in an ECS?

Hey I am currently working on a small entity component system where there are classes like EntityManager, ComponentManager and SystemManager that are only instantiated once and heavily communicate with each other.
I created a class world which owns all the managers and acts as the center for all communication between the managers. Making all the Managers static would make a lot of things much easier, more understandable and I wouldn't even need the world class.
I know though that static classes (I know "static classes" don't exist but I mean classes with only static members) act as if they were global and global variables are Bad®.
So I wonder what is recommended to do in this case
Thanks for your answers
Che
Edit:
The World class looks like this:
class World
{
public:
EntityManager* entityManager;
ComponentManager<PositionComponent>* componentManager;
MovementSystem* movementSystem;
Entity e;
public:
World(sf::RenderWindow& window);
void update();
};
To communicate each Manager needs a pointer to the world to access the other managers. Like this world->entityManager->getEntitys()
(I suggest that the project is a game or something close to it)
I don't suggest you to make all members static. The main problem with it that you're loosing control on object's lifetime. You can't destroy and create new object at runtime easily because there is no object. For example, if you want to change a manager at runtime you'll have to implement cleanup code manually. In case of C++ objects C++ helps you with errors/warnings, default values and class members by value.
There are few popular ways to implement and use managers in gamedev:
Use Singleton pattern. In this case class have one static method that returns link to non-static object.
Pass dependencies that method requires during the method call manually.
Singleton pattern, I think, is the best way in terms of price-quality ratio for you. Despite on all criticism of this pattern it does its job well (most of game projects I saw used Singleton approach to implement manager classes).
There is an important thing I want to suggest you about this pattern. Don't use default implementation of Singleton pattern. Create methods for creating and destroying object instead of hiding it inside of getter. Here's simple example of glue code for a manager:
class Manager {
private:
static Manager* ms_manager;
public:
static void CreateManager() { ms_manager = new Manager(); }
static void DestroyManager() { delete ms_manager; }
static Manager* GetInstance() { return ms_manager; }
};
Usage is:
Manager::GetInstance()->SomeMethod();
Passing dependencies approach has its own advantages. It may sounds too difficult to pass everything in every Update method but it's not. You can create context class, set all dependencies there and pass it to every method that needs it. It's almost like your World class but it must be structure with minimum of code and no dependencies. Don't store there any game objects by value (only primitives, geometry vectors and stuff like this). It may be something like this:
struct Context {
EntityManager* entityManager;
ComponentManager<PositionComponent>* componentManager;
MovementSystem* movementSystem;
Entity* rootEntity;
};
Usage is:
GameObject::Update(Context& context) { context.entityManager->SomeMethod(); }
The point of this approach that you can tune context for some objects at runtime. For example, if you have LODs you can save in context current LOD level and change it at runtime for some objects depends on distance to the camera.

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.

Is it okay when a base class has only one derived class?

I am creating a password module using OOD and design patterns. The module will keep log of recordable events and read/write to a file. I created the interface in the base class and implementation in derived class. Now I am wondering if this is sort of bad smell if a base class has only one derived class. Is this kind of class hierarchy unnecessary? Now to eliminate the class hierarchy I can of course just do everything in one class and not derive at all, here is my code.
class CLogFile
{
public:
CLogFile(void);
virtual ~CLogFile(void);
virtual void Read(CString strLog) = 0;
virtual void Write(CString strNewMsg) = 0;
};
The derived class is:
class CLogFileImpl :
public CLogFile
{
public:
CLogFileImpl(CString strLogFileName, CString & strLog);
virtual ~CLogFileImpl(void);
virtual void Read(CString strLog);
virtual void Write(CString strNewMsg);
protected:
CString & m_strLog; // the log file data
CString m_strLogFileName; // file name
};
Now in the code
CLogFile * m_LogFile = new CLogFileImpl( m_strLogPath, m_strLog );
m_LogFile->Write("Log file created");
My question is that on one hand I am following OOD principal and creating interface first and implementation in a derived class. On the other hand is it an overkill and does it complicate things? My code is simple enough not to use any design patterns but it does get clues from it in terms of general data encapsulation through a derived class.
Ultimately is the above class hierarchy good or should it be done in one class instead?
No, in fact I believe your design is good. You may later need to add a mock or test implementation for your class and your design makes this easier.
The answer depends on how likely it is that you'll have more than one behavior for that interface.
Read and write operations for a file system might make perfect sense now. What if you decide to write to something remote, like a database? In that case, a new implementation still works perfectly without affecting clients.
I'd say this is a fine example of how to do an interface.
Shouldn't you make the destructor pure virtual? If I recall correctly, that's the recommended idiom for creating a C++ interface according to Scott Myers.
Yes, this is acceptable, even with only 1 implementation of your interface, but it may be slower at run time (slightly) than a single class. (virtual dispatch has roughly the cost of following 1-2 function pointers)
This can be used as a way of preventing dependencies on clients on the implementation details. As an example, clients of your interface do not need to be recompiled just because your implementation gets a new data field under your above pattern.
You can also look at the pImpl pattern, which is a way to hide implementation details without using inheritance.
Your model works well with the factory model where you work with a lot of shared-pointers and you call some factory method to "get you" a shared pointer to an abstract interface.
The downside of using pImpl is managing the pointer itself. With C++11 however the pImpl will work well with being movable so will be more workable. At present though, if you want to return an instance of your class from a "factory" function it has copy semantic issues with its internal pointer.
This leads to implementers either returning a shared pointer to the outer class, which is made non-copyable. That means you have a shared pointer to one class holding a pointer to an inner class so function calls go through that extra level of indirection and you get two "new"s per construction. If you have only a small number of these objects that isn't a major concern, but it can be a bit clumsy.
C++11 has the advantage of both having unique_ptr which supports forward declaration of its underlying and move semantics. Thus pImpl will become more feasible where you really do know you are going to have just one implementation.
Incidentally I would get rid of those CStrings and replace them with std::string, and not put C as a prefix to every class. I would also make the data members of the implementation private, not protected.
An alternative model you could have, as defined by Composition over Inheritance and Single Responsibility Principle, both referenced by Stephane Rolland, implemented the following model.
First, you need three different classes:
class CLog {
CLogReader* m_Reader;
CLogWriter* m_Writer;
public:
void Read(CString& strLog) {
m_Reader->Read(strLog);
}
void Write(const CString& strNewMsg) {
m_Writer->Write(strNewMsg);
}
void setReader(CLogReader* reader) {
m_Reader = reader;
}
void setWriter(CLogWriter* writer) {
m_Writer = writer;
}
};
CLogReader handles the Single Responsibility of reading logs:
class CLogReader {
public:
virtual void Read(CString& strLog) {
//read to the string.
}
};
CLogWriter handles the Single Responsibility of writing logs:
class CLogWriter {
public:
virtual void Write(const CString& strNewMsg) {
//Write the string;
}
};
Then, if you wanted your CLog to, say, write to a socket, you would derive CLogWriter:
class CLogSocketWriter : public CLogWriter {
public:
void Write(const CString& strNewMsg) {
//Write to socket?
}
};
And then set your CLog instance's Writer to an instance of CLogSocketWriter:
CLog* log = new CLog();
log->setWriter(new CLogSocketWriter());
log->Write("Write something to a socket");
Pros
The pros to this method are that you follow the Single Responsibility Principle in that every class has a single purpose. It gives you the ability to expand a single purpose without having to drag along code which you would not modify anyways. It also allows you to swap out components as you see fit, without having to create an entire new CLog class for that purpose. For instance, you could have a Writer that writes to a socket, but a reader that reads a local file. Etc.
Cons
Memory management becomes a huge concern here. You have to keep track of when to delete your pointers. In this case, you'd need to delete them on destruction of CLog, as well as when setting a different Writer or Reader. Doing this, if references are stored elsewhere, could lead to dangling pointers. This would be a great opportunity to learn about Strong and Weak references, which are reference counter containers, which automatically delete their pointer when all references to it are lost.
No. If there's no polymorphism in action there's no reason for inheritance and you should use the refactoring rule to put the two classes into one. "Prefer composition over inheritance".
Edit: as #crush commented, "prefer composition over inheritance" may not be the adequate quotation here. So let's say: if you think you need to use inheritance, think twice. And if ever you are really sure you need to use it, think about it once again.

Singletons alternative

I have a pretty simple game engine. It uses several singletons(I'll enumerate some of them).
Resource Manager
Render Engine
Events Manager
Factory
etc
These singletons have many calls from one to another. I'll take Events Manager sample usage:
Any object derived from Listener can add itsel as a listener for some events just like this EventsManager->RegisterListener(this, &SomeClass::SomeMethod); (event type is deduced by SomeMethod parameter)
Any other object can fire an event like this EventsManager->PushEvent(SomeEvent);
After some synchronization the event reaches to all listeners. This is very a simple usage for EventsManager when it is singleton.
Similar behavior is with other singletons. I want to remove the singletons, but my main problem is that I want to keep the code simple to use from the "user point of view" as it is now. I read some techniques of doing this, but most of the make the initialization/usage of the classes more complicated. I know this topic was discused many times on SO, but no answer is appropriate for my programming philosophy - to keep everything as simple as possible.
I don't want to have complicated definition/initialization for my classes like:
SomeClass<EventManager, RenderEngine,...>
or
SomeClass::SomeClass(EventsManager, RenderEngine...)
Can you please give me some advice on this topic?
You could have a global "game" object that creates an instance of each of the classes that are currently singletons
For the specific example of your EventManager; your Listener base class could provide implementations of a register method and a push method that derived classes can call.
A skeleton definition:
class Listener
{
public:
virtual void ReceiveMessage( ... ) = 0;
protected:
void Register()
{
GetEventManagerSomehow()->RegisterListener( this, etc );
}
void PushEvent( etc )
{
GetEventManagerSomehow()->PushEvent( etc );
}
}
To solve the specific problem of detecting resource leaks in your singletons, give each singleton class a shutdown method that destroys the instance.
class Singleton
{
// ...
static Singleton * GetInstance()
{
if (instance == NULL)
instance = new Singleton;
return instance;
}
static void Shutdown()
{
delete instance;
instance = NULL;
}
static Singleton * instance;
};
Singleton * Singleton::instance = NULL;
Not really an answer, but maybe too long for a comment.
Dependency injection is a very good alternative to singletons: You create instances in the main function of your program and you pass them to "modules" (which are main classes), so they can use them locally. This means that for these classes you will have the "complicated" constructors that you don't want.
However, The complexity should only be limited to some classes and passing some dependent "modules" are in my point of view not that complex. As a bonus, you can find out dependencies between modules by just looking at the constructors or at the main function.
Dependency injection is used a lot because it does solve the issue that you are seeing (and more, like unit testing) with only a very limited amount of added complexity.

OO Programming Design question: Global Object part II

Sorry for reposting this, but for some reason I can not add comments to my older
post. Some people wanted to know the exact error message I get when trying to do
the following:
I have probably a quite simple problem but I did not find a proper
design decision yet. Basically, I have 4 different inherited classes and
each of those classes has more than 10 methods.
Each of those classes should make use of the same TCP Socket; this
object keeps a socket open to the server throughout program execution.
My idea was to have the TCP obejct declared as "global" so that all
other classes can use it:
classTCP TCPSocket;
class classA
{
private:
public:
classA();
virtual void method1();
...
};
class classB
{
private:
public:
classB();
virtual void method1();
...
};
and so on for classC and classD...
Unfortunately, when declaring it like this my Symbian GCC-E compiler gives me the
following error message
elf2e32 : Error: E1027: ELF File contains initialized writable data.
So I am wondering if there is any other way I could declare this
TCP object so that it is available for ALL the other classes and its
methods? classA() is the first method that will be called when
initialising this subsystem.
Many thanks!
There is very elegant way to retrieve static instances on demand.
classTCP& SingletonInstance()
{
static classTCP instance;
return instance;
}
Idea is using c++ feature to initialize local static variables only on demand.
You can support a class-wide static member by allowing both classA and classB to inherit from the same parent.
class BaseTCP {
static classTCP tcp;
// ...
};
class classA : BaseTCP {
// ...
};
class classB : BaseTCP {
// ...
};
Now classA and ClassB both share the same static member. The stipulation is that you now have to declare the static member outside of the BaseTCP class someplace, similar to:
classTCP BaseTCP::tcp;
Depending on your situation, this may be overkill...
Instead of using singletons, why don't you just create a classTCP instance and pass references to the other objects, each of which owns a reference (or pointer) to the single instance of classTCP.
This offers a much more flexible design - I think singletons generally suck and have much more limited use that generally believed. If you use a singleton, your classes classA, classB etc... have no option but to use the singleton instance. Using a more standard object composition design, you free the whole thing up.
Ask yourself questions like, what if I want the application to talk to >1 server? or what if I want to write some unit test code for classA? Writing unit test code for networking applications is a lot easier when you don't need to use real sockets but can use dummy ones that simply hold the chunks of data in ram. Add a comment if you want an example, because I'm off for lunch now:)
Doing it the way I suggest does not add significant complexity to the overall design but makes it much more open.
A Singleton pattern.