C++: managing a set of objects so that the held objects can access the data structure holding them

I store pointers to all instances of class Cell in a linked list. The std::list<Cell*> cells is stored in a class named Game. The method Game::update() iterates trought all instances of Cell held in the list cells, and calls each cell's Cell::update() method. If the Cell::update() method finds out at some point that the cell is ready to divide, it needs to push_back() a pointer to the new cell to cells in order for the new cell to be updateable. But how can I refer to Game::cells within the cell in order to do that? I have considered the following options:

  • Defining std::list<Cell*> cells in global scope instead.
    • nasty and makes it impossible to have more than one Game
  • Making std::list<Cell*> cells a static member of Cell
    • better than the global var but still prevents the use of multiple Game instances
  • Passing a reference to the current game's Game::cells as a parameter to the Cell's constructor and subsequently storing a copy of that reference in the newly constructed cell instance
    • I think it is a little inflexible
  • Passing a reference to the current game's Game::cells as a parameter to the Cell::update() method

Are there more elegant solutions to utilize?


I would not introduce an unnecessary dependence between Cell and Game, if all Game does is to call methods on Cells and hold instances of them.

You could instead return new Cells (or none) from Cell::update() and let Game decide what to do, most probably add them to the list. You could also define a new function for this in Cell, something like Cell::splitCell() and let Cell::update() only update properties of Cell objects (as the name would suggest).

Need Your Help

Why NullPointerException occured in WebView?

android webview nullpointerexception fragment

I tried every examples by Googling and it doesn't work.

When does Eclipse xml editor show element documentation if you hoover over it

xml eclipse xsd xml-editor

How is it with xml editor and documents that have xsd available ? I remember pop-up documentation when I was hoovering over the elements, but I haven't seen it for past months...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.