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 know if it's bad practice have static container in class store pointers class' objects can accessed base classes of program. game , saw on sdltutorials dot com, , find useful. allow me have neat structure game , don't see downside doing this, know have careful "global" access , maybe there's negative effect i'm not seeing right now.
here context/example. game has base class basic methods such loop(), render(), playaudio(), cleanmemory(). idea have individual objects have same methods being executed inside base method. example in pseudocode:
game::render() { (iterate enemies in static container) { current_enemy::render(); } }
to sure, static member inside class this:
static std::vector<enemy*> enemylist;
so way, when game executing base render() method, example, can iterate enemies in enemies' class static container , execute individual render() methods, same environment objects, player, etc.
i make sure i'm aware of downside/complication/limitation might encounter if choose method build game, because don't see right know have careful static , global stuff.
thanks time.
it convenient, static
variable or singleton
nothing more global variables; , having global variables comes drawbacks:
- the dependencies of function become unclear: global rely upon ?
- the re-entrancy of function compromised: if
current_enemy.render()
accidentally callsgame::render()
? it's infinite recursion! - the thread-safety of function compromised, unless proper synchronization takes place, in case serialized access global variable bog down performance of concurrent code (because of amdahl's law)
it might seem painful , pointless explicitly pass reference instance of game
wherever need to, leaves clear path of dependencies can followed , software grows appreciate explicitness.
and there is, of course, said transforming program have two instances of game
. while might seem incongruous in precise situation, in general wise not assume never necessary in future, no oracles.
Comments
Post a Comment