c++ - Avoid cyclic references -


i'm building small game sdl. i've class gameobject main class representing objects in game. different behaviors solved components can inject outside:

#include "input.h" class gameobject { public:     void setinput(input* input)     {         input->setgameobject(this);         this->input = input;     } }   class gameobject; // cannot #include "gameobject.h" class input { private:     gameobject* object; public:     void update(float elapsedtime)     {         // fancy stuff on gameobject object     }     void setgameobject(gameobject* object)     {         this->object = object;     } } 

the input class has work on gameobject instance. have cyclic reference not idea guess?

edit: adjusted example make clearer. have of these components input class , i've use class gameobject; statement since cannot include header file. if understood correctly i've cyclic reference!? solve have use interface , add setgameobject(inputinterface* object). cannot predict functions/member needed access of gameobject because there different components used (e.g. playerinput, demoinput, aiinput, ...).

it seems you're using raw pointers (personally think bad idea), see no problem in having cyclic reference, remember check null.

if using smarter pointer types, in case use strong reference in 1 direction (the 1 "contains" other) , weak reference in other (the 1 needs way communicate).

for example, game object owns input mechanism; input mechanism needs way communicate input game object.

std::weak_ptr used break circular references of std::shared_ptr.

see: http://en.cppreference.com/w/cpp/memory/weak_ptr

also, check if input needs hold on whole game object, or some object has interface. in case, event mechanisms or delegate pattern remove hard dependencies.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -