HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppModerate

C++ Vector memory management in Game of Life

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lifegamememorymanagementvector

Problem

I'm writing a simulator for Conway's Game of Life (http://en.wikipedia.org/wiki/Conway's_Game_of_Life) in C++ and I'm trying to make the code as idiomatic as possible.

The central object is a double array to represent the board:

typedef vector > Board;


My main method has a Board b as a local variable, and I'm passing the board to several methods that update the board, draw the board, and so on. Is it better (that is, more efficient and/or idiomatic) to use methods like

void update(Board *board);

int main() {
   Board b;
   //...
   update(&b);
   //...
}


or in this way:

void update(Board & board);

int main() {
   Board b;
   //...
   update(b);
   //...
}


Which is the proper choice for idiomatic C++?

Solution

One rules of thumb to write idiomatic C++ is:


Use references where you can and pointers where you have to.

It's especially true for argument passing to a variable.
In your case, you have the choice, so use references, for all the reasons cited by Ilya and also just because you won't have any * to put everywhere in your function. Your code might be clearer that way.

Context

StackExchange Code Review Q#14972, answer score: 11

Revisions (0)

No revisions yet.