D (dlang): Can a function call in constructor & destructor converted to RAII in a object lifetime scope? - d

Background: In one of my projects, I have an abstract class with static interface to track resource usage of other objects. The Track class looks like this:
https://github.com/mkoskim/games/blob/master/engine/util/track.d
As you can see, other classes/objects call add & remove functions. Track class takes an object as an argument, and uses the information extracted from object to track usage: current implementation creates lookup table containing reference counters from class name. The output from tracking looks something like this:
D has automatic memory management, so there is no point to track that. But these certain objects hold external resources - in this case, GPU side things like textures, vertex buffers and such - and I like to see that those are freed in correct situations, that is, e.g. switching to new level in a game works correctly, and there is no loose references left to objects in previous level.
Problem: Now, although it works, it is a bit clumpsy mechanism in my opinion. I need to add calls to class constructor & destructor to keep it tracked. In many cases, my classes have many different constructors, and I need to make sure that Track::add() is called once and only once during the construction phase. For example,
https://github.com/mkoskim/games/blob/master/engine/gpu/shader.d#L326
...here you can see, starting at line 334, one example of constructor "construction". The thing works, but whenever touching to constructors and their call tree, I need to be careful with the tracking.
Question: I am pretty sure D has some powerful tools to automatize these kinds of things. I have been mainly looking for mechanics similar to scope() to inject function calls to object lifetime (creation and deletion).
There is certainly some other possible solutions. One way, familiar from C++, would of course to inherit tracked objects from Track(ed) class, like
class Shader : Tracked { ... }
But I would not like to use that myself, as it would lead to problems if the class is anyways derivate from some other class. I am of course open for suggestions making that work somehow, e.g.
class Shader : BaseShader, Tracked { ... }
Another way might make composed classes, so that tracker object would be constructed & destructed according to its parent? Something like:
class Shader {
...
private Tracked tracked = new Tracked(self);
...
this() { ... }
this(int) { ... }
this(string) { ... }
...
~this() { ... }
}
Personally I feel it bit odd, that I need to attach extra, unnecessary memory blocks in form of Tracked object to other objects (as I only need to inject calls to parent class constructor and destructor).
What other ways there are?
If this felt confusing, don't hesitate to ask me to clarify the question.

Related

Object propagation

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!

High Level Configuration of Constructor Injection in C++

My questions are specifically dealing with dependency injection through the constructor. I understand the pros/cons of service locator pattern, constructor/setter injection, and their flavors, however there is something I can't seem to get past after choosing pure constructor injection. After reading many materials for testable design, including a thorough perusing of Miško Hevery's blog (specifically this post) I'm at the following situation:
Assume I'm writing a C++ program, and I have correctly injected my dependencies through their constructors. For readability I have given myself a high-level object which has a single Execute() function called from main:
int main(int argc, char* argv[]) {
MyAwesomeProgramObject object(argc, argv);
return object.Execute();
}
Execute()'s responsibility is to simply wire up all required objects and kick off the highest level object. The highest level object requires a couple dependencies and those objects required a few objects and so on and so on, implying a function that looks like this:
MyAwesomeProgramObject::Execute() {
DependencyOne one;
DependencyTwo two;
DependencyThree three;
MidLevelOne mid_one(one);
MidLevelTwo mid_two(two, three);
// ...
MidLevelN mid_n(mid_dependencyI, mid_dependencyJ, mid_dependencyK);
// ...
HighLevelObject1 high_one(mid_one, mid_n);
HighLevelObject2 high_two(mid_two);
ProgramObject object(high_one, high_two);
return object.Go();
}
From what I take from Miško's blog (and I would ask him, but figured he wouldn't have time to get back to me), this is the only way to satisfy pure constructor injection of dependencies.
In the blog post mentioned, he states we should have factories on a per object lifetime level, but this is essentially what Execute is doing, making my code look identical to his example:
AuditRecord audit = new AuditRecord();
Database database = new Database(audit);
Captcha captcha = new Captcha();
Authenticator authenticator =
new Authenticator(database, captcha, audit);
LoginPage = new LoginPage(audit, authenticator);
Questions:
Is this the correct approach?
Is this a pattern that I'm not aware of (seems similar to Maven's context.xml)?
For pure constructor injection, do I simply suffer the cost of "upfront" allocation?
Note that your different examples are contradictory. At first you show creating objects on the stack, and your last example allocates objects.
Objects on the stack are somewhat dangerous, but just fine in most cases. The main problem is to give another object that has a longer lifetime than your function an object pointer when that object comes from the stack... when that long lived object tries to access the object on the stack after the function returned, you have a problem. If all the objects have a stack lifetime, then you're fine.
Personally, I started using shared pointers and I find that to be the ultimate in easing the management of a large number of objects.
std::shared_ptr<foo> foo_object(new foo);
std::shared_ptr<blah> foo_object(new blah(foo));
In this way blah can hold a copy of the foo shared pointer forever and everything works as expected, even between function boundaries. Not only that, the shared pointer is NULL on creation, and auto-deleted on deletion (when the last shared pointer is deleted, of course.) And you can use weak pointer in objects that do not need the pointer to always be set...
Otherwise, I think that what you are trying to do works to a certain extend. In my world, it is often that things get created at a later time so I need a setter. However, constructor injections are very useful to force the user to properly initialize your object (i.e. I often create read-only objects, no setters, which are 100% initialized on construction, very practical, very safe!)

Should I use a public pointer?

I am currently working on a game where I have a couple of classes which each handles their own gameobjects. For these classes to actually represent something in the game they need to use another class which is the animation_manager.
The animation_manager handles the loading, drawing and moving of objects on the screen and is created at startup.
What would be the smartest way of passing the manager to the classes which handles the gameobjects?
Should it be done by a public pointer, by assigning it to a static pointer in the object class which every gameobject inherits from or should I simply just pass it as a pointer to the gameobjects/objects class constructor?
I am using C++03 so no new fancy fixes :P
EDIT 1:
There has been a lot of good suggestions and I am thankful for that.
Now I will not use weak pointers since I dont need the object handlers to take care of the deletion of the pointer as its going to exist from the beginning to the end of the program.
Singletons wont fit my needs either as I dont want any class to have access to it.
One thing that came to mind when reading the replies is: Would it be a good idea to make a static reference for the anim_handler in the Object class which all the handling classes inherits from?
I'd prefer the passing by constructor.
This way you can establish an invariant (i.e. the manager is always present) whereas later setting a field does not ensure it's always done.
Like thomas just posted you should use a shared_ptr or something similar (if not using C++11).
I try not to use static fields (except for constants) since it prevents you to use different manager objects for each gameobject. (Think of a debugging/logging manager class, or another wrapped manager).
You can keep this shared manager object in a shared pointer which is added to C++11 (or you can use Boost library) standard as shared_ptr.
It has a reference counting mechanism such that you do not have to worry about the ownership and memory management of related object.
Every gameobject can keep a shared pointer member to your animation_manager.
If your animator_manager is a unique object, another approach could be defining it as a signleton, eventually removing the need for storing any reference to it in the gameobjects handling classes and using some sort of static method like animation_manager::getInstance() to use it.
The performance impact could be easily minimized by reducing the calls to the getInstance() method, but it really depends on your design, can't be sure it would fit.
you should give it as a reference (if possible a reference to a const), not a pointer. Only if you would have a class hierarchy of animation managers a pointer (if possible const to a const) would make sense. In the latter case, you should consider using boost's shared_ptr. If move to C++11 later, the changes to C++11's shared_ptr are minimal.
From the design point of view, you might also think about using an observer pattern, so the animation manager can decide on its own when it is the right time to render without having too much boilerplate code.
Passing a reference would be the most favorable way when thinking as a good software architect, because it will allow easier testing and mocking.
However, a game(engine) is - in my opinion - such a special case of software where "good patterns" can be counterproductive sometimes. You will nearly always end up in the situation that you need some manager classes everywhere.
You might want to look at the god-object anti-pattern, to make all common managers available globally. I use one(!) globally accessible instance of an "Application"-instance, which contains some bootstrapping code and references to the most common manager classes, like this:
// application.h
class CApplication {
void init(int argc, char **argv); // init managers & co here
void shutdown();
void run();
CMemoryManager * memory;
CSystemManager * system;
CAudioManager * sound;
CInputManager * input;
};
// globals.h
CApplication * app;
// main.c
#include "globals.h"
int main(int argc, char ** argv) {
app = new CApplication();
app->init(argc, argv);
app->run();
app->shutdown();
return 0;
}
// some_other_file.cpp
#include "globals.h"
void doSomething() {
// ...
app->input->keyDown(...);
// ...
}
Bad style? Probably. Does it work? For me it does. Feedback is also welcome as comment!
I'm adding another answer because it's quite a different approach, when compared with the previuos one.
First of all I should clarify that I'm not experienced in game programming! :)
Anyway, as I was suggesting in my previous comments, maybe, I would take a different route. Immagine that you have a "game field" with walls and other static elemnts, and a number of "actors", like monsters, the player alter ego and so on...
I would probably write an ancestor "Actor", subcalssing "Player" and "Enemy" classes, then subclassing "Enemy" into "Dragon", "Zombie", "Crocodile" and so on. Maybe Actor could have a bounch of common attributes, like "location", "speed", "strenght", "energy", "direction", "destination" and a status, say "moving", "sleeping", "eating the player", "being eated"...
A typical game iteration, could be something like:
1) get input from the player
2) call a method of the player actor object, something like:
player->move(east, fast);
3) cycle trough a list of actors to update their status, say:
for (int i(0); i < enemies.size(); i++) {
// Checks the player position in the gamefield and setup a strategy to eat him
enemies[i]->updateStatus(player, gamingField);
}
4) cycle trough the list of actors and move them:
animator->animate(player);
for (int i(0); i < enemies.size(); i++) {
animator->animate(enemies[i]);
}
5) check if something interesting has happened (the player has been eaten by the crocodile)
I mean: this is a totally different approach, but I think that isolating the actors logic could be a good idea, and you could avoid the original problem completely.
It seems to me that there are no explicit answer for this question, but rather multiple ways of doing it which each has their own opinion on.
In case anyone else have the same question I am going to list them below:
Shared_Pointer:
This method will keep track of the amount of used pointers pointing to the address and if that count hits zero, then it will deallocate the memory. Is available in C++11 and the boost library.
A shared pointer can be passed to other objects the same way as a normal pointer.
Suggested by ogni42
Passed by constructor:
A pointer or reference can be passed to the object when it is being constructed. The upside of using a reference is that the programmer can't accidentally use delete on the pointer.
Prefered by Onur.
Use of singletons
Singletons are an unique extern class which holds a pointer to the object which can be accessed through a function.
This was suggested by Albert
Global variables
Simply a globally declared variables. Personally I do not recommend these as they can become a mess as they become available even from code which you wont need them in.
Suggested by Sir PanCake
static variables
This is what I ended up using. I made it so that only objects which inherited from my Object class could access the anim_handler. The way I did this was by declaring Object a friend of my anim_handler and then I made the static variable to retrieve the handler protected
Anyways, thanks for the support everyone! I appreciates it a lot and I even learned something new! :)

delete this & private destructor

I've been thinking about the possible use of delete this in c++, and I've seen one use.
Because you can say delete this only when an object is on heap, I can make the destructor private and stop objects from being created on stack altogether. In the end I can just delete the object on heap by saying delete this in a random public member function that acts as a destructor. My questions:
1) Why would I want to force the object to be made on the heap instead of on the stack?
2) Is there another use of delete this apart from this? (supposing that this is a legitimate use of it :) )
Any scheme that uses delete this is somewhat dangerous, since whoever called the function that does that is left with a dangling pointer. (Of course, that's also the case when you delete an object normally, but in that case, it's clear that the object has been deleted). Nevertheless, there are somewhat legitimate cases for wanting an object to manage its own lifetime.
It could be used to implement a nasty, intrusive reference-counting scheme. You would have functions to "acquire" a reference to the object, preventing it from being deleted, and then "release" it once you've finished, deleting it if noone else has acquired it, along the lines of:
class Nasty {
public:
Nasty() : references(1) {}
void acquire() {
++references;
}
void release() {
if (--references == 0) {
delete this;
}
}
private:
~Nasty() {}
size_t references;
};
// Usage
Nasty * nasty = new Nasty; // 1 reference
nasty->acquire(); // get a second reference
nasty->release(); // back to one
nasty->release(); // deleted
nasty->acquire(); // BOOM!
I would prefer to use std::shared_ptr for this purpose, since it's thread-safe, exception-safe, works for any type without needing any explicit support, and prevents access after deleting.
More usefully, it could be used in an event-driven system, where objects are created, and then manage themselves until they receive an event that tells them that they're no longer needed:
class Worker : EventReceiver {
public:
Worker() {
start_receiving_events(this);
}
virtual void on(WorkEvent) {
do_work();
}
virtual void on(DeleteEvent) {
stop_receiving_events(this);
delete this;
}
private:
~Worker() {}
void do_work();
};
1) Why would I want to force the object to be made on the heap instead of on the stack?
1) Because the object's lifetime is not logically tied to a scope (e.g., function body, etc.). Either because it must manage its own lifespan, or because it is inherently a shared object (and thus, its lifespan must be attached to those of its co-dependent objects). Some people here have pointed out some examples like event handlers, task objects (in a scheduler), and just general objects in a complex object hierarchy.
2) Because you want to control the exact location where code is executed for the allocation / deallocation and construction / destruction. The typical use-case here is that of cross-module code (spread across executables and DLLs (or .so files)). Because of issues of binary compatibility and separate heaps between modules, it is often a requirement that you strictly control in what module these allocation-construction operations happen. And that implies the use of heap-based objects only.
2) Is there another use of delete this apart from this? (supposing that this is a legitimate use of it :) )
Well, your use-case is really just a "how-to" not a "why". Of course, if you are going to use a delete this; statement within a member function, then you must have controls in place to force all creations to occur with new (and in the same translation unit as the delete this; statement occurs). Not doing this would just be very very poor style and dangerous. But that doesn't address the "why" you would use this.
1) As others have pointed out, one legitimate use-case is where you have an object that can determine when its job is over and consequently destroy itself. For example, an event handler deleting itself when the event has been handled, a network communication object that deletes itself once the transaction it was appointed to do is over, or a task object in a scheduler deleting itself when the task is done. However, this leaves a big problem: signaling to the outside world that it no longer exists. That's why many have mentioned the "intrusive reference counting" scheme, which is one way to ensure that the object is only deleted when there are no more references to it. Another solution is to use a global (singleton-like) repository of "valid" objects, in which case any accesses to the object must go through a check in the repository and the object must also add/remove itself from the repository at the same time as it makes the new and delete this; calls (either as part of an overloaded new/delete, or alongside every new/delete calls).
However, there is a much simpler and less intrusive way to achieve the same behavior, albeit less economical. One can use a self-referencing shared_ptr scheme. As so:
class AutonomousObject {
private:
std::shared_ptr<AutonomousObject> m_shared_this;
protected:
AutonomousObject(/* some params */);
public:
virtual ~AutonomousObject() { };
template <typename... Args>
static std::weak_ptr<AutonomousObject> Create(Args&&... args) {
std::shared_ptr<AutonomousObject> result(new AutonomousObject(std::forward<Args>(args)...));
result->m_shared_this = result; // link the self-reference.
return result; // return a weak-pointer.
};
// this is the function called when the life-time should be terminated:
void OnTerminate() {
m_shared_this.reset( NULL ); // do not use reset(), but use reset( NULL ).
};
};
With the above (or some variations upon this crude example, depending on your needs), the object will be alive for as long as it deems necessary and that no-one else is using it. The weak-pointer mechanism serves as the proxy to query for the existence of the object, by possible outside users of the object. This scheme makes the object a bit heavier (has a shared-pointer in it) but it is easier and safer to implement. Of course, you have to make sure that the object eventually deletes itself, but that's a given in this kind of scenario.
2) The second use-case I can think of ties in to the second motivation for restricting an object to be heap-only (see above), however, it applies also for when you don't restrict it as such. If you want to make sure that both the deallocation and the destruction are dispatched to the correct module (the module from which the object was allocated and constructed), you must use a dynamic dispatching method. And for that, the easiest is to just use a virtual function. However, a virtual destructor is not going to cut it because it only dispatches the destruction, not the deallocation. The solution is to use a virtual "destroy" function that calls delete this; on the object in question. Here is a simple scheme to achieve this:
struct CrossModuleDeleter; //forward-declare.
class CrossModuleObject {
private:
virtual void Destroy() /* final */;
public:
CrossModuleObject(/* some params */); //constructor can be public.
virtual ~CrossModuleObject() { }; //destructor can be public.
//.... whatever...
friend struct CrossModuleDeleter;
template <typename... Args>
static std::shared_ptr< CrossModuleObject > Create(Args&&... args);
};
struct CrossModuleDeleter {
void operator()(CrossModuleObject* p) const {
p->Destroy(); // do a virtual dispatch to reach the correct deallocator.
};
};
// In the cpp file:
// Note: This function should not be inlined, so stash it into a cpp file.
void CrossModuleObject::Destroy() {
delete this;
};
template <typename... Args>
std::shared_ptr< CrossModuleObject > CrossModuleObject::Create(Args&&... args) {
return std::shared_ptr< CrossModuleObject >( new CrossModuleObject(std::forward<Args>(args)...), CrossModuleDeleter() );
};
The above kind of scheme works well in practice, and it has the nice advantage that the class can act as a base-class with no additional intrusion by this virtual-destroy mechanism in the derived classes. And, you can also modify it for the purpose of allowing only heap-based objects (as usually, making constructors-destructors private or protected). Without the heap-based restriction, the advantage is that you can still use the object as a local variable or data member (by value) if you want, but, of course, there will be loop-holes left to avoid by whoever uses the class.
As far as I know, these are the only legitimate use-cases I have ever seen anywhere or heard of (and the first one is easily avoidable, as I have shown, and often should be).
The general reason is that the lifetime of the object is determined by some factor internal to the class, at least from an application viewpoint. Hence, it may very well be a private method which calls delete this;.
Obviously, when the object is the only one to know how long it's needed, you can't put it on a random thread stack. It's necessary to create such objects on the heap.
It's generally an exceptionally bad idea. There are a very few cases- for example, COM objects have enforced intrusive reference counting. You'd only ever do this with a very specific situational reason- never for a general-purpose class.
1) Why would I want to force the object to be made on the heap instead of on the stack?
Because its life span isn't determined by the scoping rule.
2) Is there another use of delete this apart from this? (supposing that this is a legitimate use of it :) )
You use delete this when the object is the best placed one to be responsible for its own life span. One of the simplest example I know of is a window in a GUI. The window reacts to events, a subset of which means that the window has to be closed and thus deleted. In the event handler the window does a delete this. (You may delegate the handling to a controller class. But the situation "window forwards event to controller class which decides to delete the window" isn't much different of delete this, the window event handler will be left with the window deleted. You may also need to decouple the close from the delete, but your rationale won't be related to the desirability of delete this).
delete this;
can be useful at times and is usually used for a control class that also controls the lifetime of another object. With intrusive reference counting, the class it is controlling is one that derives from it.
The outcome of using such a class should be to make lifetime handling easier for users or creators of your class. If it doesn't achieve this, it is bad practice.
A legitimate example may be where you need a class to clean up all references to itself before it is destructed. In such a case, you "tell" the class whenever you are storing a reference to it (in your model, presumably) and then on exit, your class goes around nulling out these references or whatever before it calls delete this on itself.
This should all happen "behind the scenes" for users of your class.
"Why would I want to force the object to be made on the heap instead of on the stack?"
Generally when you force that it's not because you want to as such, it's because the class is part of some polymorphic hierarchy, and the only legitimate way to get one is from a factory function that returns an instance of a different derived class according to the parameters you pass it, or according to some configuration that it knows about. Then it's easy to arrange that the factory function creates them with new. There's no way that users of those classes could have them on the stack even if they wanted to, because they don't know in advance the derived type of the object they're using, only the base type.
Once you have objects like that, you know that they're destroyed with delete, and you can consider managing their lifecycle in a way that ultimately ends in delete this. You'd only do this if the object is somehow capable of knowing when it's no longer needed, which usually would be (as Mike says) because it's part of some framework that doesn't manage object lifetime explicitly, but does tell its components that they've been detached/deregistered/whatever[*].
If I remember correctly, James Kanze is your man for this. I may have misremembered, but I think he occasionally mentions that in his designs delete this isn't just used but is common. Such designs avoid shared ownership and external lifecycle management, in favour of networks of entity objects managing their own lifecycles. And where necessary, deregistering themselves from anything that knows about them prior to destroying themselves. So if you have several "tools" in a "toolbelt" then you wouldn't construe that as the toolbelt "owning" references to each of the tools, you think of the tools putting themselves in and out of the belt.
[*] Otherwise you'd have your factory return a unique_ptr or auto_ptr to encourage callers to stuff the object straight into the memory management type of their choice, or you'd return a raw pointer but provide the same encouragement via documentation. All the stuff you're used to seeing.
A good rule of thumb is not to use delete this.
Simply put, the thing that uses new should be responsible enough to use the delete when done with the object. This also avoids the problems with is on the stack/heap.
Once upon a time i was writing some plugin code. I believe i mixed build (debug for plugin, release for main code or maybe the other way around) because one part should be fast. Or maybe another situation happened. Such main is already released built on gcc and plugin is being debugged/tested on VC. When the main code deleted something from the plugin or plugin deleted something a memory issue would occur. It was because they both used different memory pools or malloc implementations. So i had a private dtor and a virtual function called deleteThis().
-edit- Now i may consider overloading the delete operator or using a smart pointer or simply just state never delete a function. It will depend and usually overloading new/delete should never be done unless you really know what your doing (dont do it). I decide to use deleteThis() because i found it easier then the C like way of thing_alloc and thing_free as deleteThis() felt like the more OOP way of doing it

C++ game designing & polymorphism question

I'm trying to implement some sort of 'just-for-me' game engine and the problem's plot goes the following way:
Suppose I have some abstract interface for a renderable entity, e.g. IRenderable.
And it's declared the following way:
interface IRenderable {
// (...)
// Suppose that Backend is some abstract backend used
// for rendering, and it's implementation is not important
virtual void Render(Backend& backend) = 0;
};
What I'm doing right now is something like declaring different classes like
class Ball : public IRenderable {
virtual void Render(Backend& backend) {
// Rendering implementation, that is specific for
// the Ball object
// (...)
}
};
And then everything looks fine. I can easily do something like std::vector<IRenderable*> items, push some items like new Ball() in this vector and then make a call similiar to foreach (IRenderable* in items) { item->Render(backend); }
Ok, I guess it is the 'polymorphic' way, but what if I want to have different types of objects in my game and an ability to manipulate their state, where every object can be manipulated via it's own interface?
I could do something like
struct GameState {
Ball ball;
Bonus bonus;
// (...)
};
and then easily change objects state via their own methods, like ball.Move(...) or bonus.Activate(...), where Move(...) is specific for only Ball and Activate(...) - for only Bonus instances.
But in this case I lose the opportunity to write foreach IRenderable* simply because I store these balls and bonuses as instances of their derived, not base classes. And in this case the rendering procedure turns into a mess like
ball.Render(backend);
bonus.Render(backend);
// (...)
and it is bad because we actually lose our polymorphism this way (no actual need for making Render function virtual, etc.
The other approach means invoking downcasting via dynamic_cast or something with typeid to determine the type of object you want to manipulate and this looks even worse to me and this also breaks this 'polymorphic' idea.
So, my question is - is there some kind of (probably) alternative approach to what I want to do or can my current pattern be somehow modified so that I would actually store IRenderable* for my game objects (so that I can invoke virtual Render method on each of them) while preserving the ability to easily change the state of these objects?
Maybe I'm doing something absolutely wrong from the beginning, if so, please point it out :)
Thanks in advance!
The fact that you are storing the different objects as members of the class shouldn't prevent you from storing pointers to them in the IRenderable* vector.
struct GameState {
Ball ball;
Bonus bonus;
vector<IRenderable*> m_items;
GameState() // constructor
{
m_items.push_back(&ball);
m_items.push_back(&bonus);
}
};
This way you also don't have to worry about freeing the pointers in m_items. They will be automatically destroyed when the GameState is destroyed.
Also, your syntax of foreach is funky.
You should really have separate subsystems in your game engine. One for rendering and another one for game logic. Your graphics subsystem should have a list of pointers to IRenderable objects. Your game logic subsystem should have its own list of objects with another interface.
Now you can easily have entities that have state but cannot be rendered and so on. You might even have a separate subsystem for audio. This should also help keep your code clean and modular.
I'm not a c++ programmer but hopefully faux-code will help...
Class Renderable has the function Render
Class Movable inherits from Renderable and also has properties such as x, y, z and functions like Move
Class Ball inherits from Movable
Now your game state can have a list of Renderable objects and, when the time comes to Render, it can just loop through them.
Other actions, like a tick of the world clock, might loop through looking for objects which are instances of Moveable and tell them to update.
If your Bonus is renderable (I couldn't tell for sure from your question) then it could subclass Collectable which subclasses Moveable.