I have the following trimmed class:
#include <vector>
#include "Tile.h"
class Board {
std::vector<Tile> boardArr;
// VVV Bad Practice? Safe?
Tile& getTileAt(unsigned int x, unsigned int y);
public:
Board(int width, int height);
};
Note that the vector remains the same size once the class is initialized; I have no methods to modify it. From what I understand, vector
s are guaranteed to not move around, unless it's required to resize, so a reference into it should be safe in this case.
From what I can tell, this should be safe. The method is private, so there shouldn't be any way for references to leak.
The best alternative to the above function is to return a copy of the Tile
, modify it, then copy the modified tile back. I found using it directly a lot cleaner, so I'd prefer it if it's safe.
This will be single-threaded, and so far, it's only use is to do simple things to a tile, like toggle an internal flag. An example of how I'm using it:
TurnResult Board::flipTile(unsigned int x, unsigned int y) {
return getTileAt(x, y).flipTile();
}
void Board::setTileFlag(unsigned int x, unsigned int y, bool flagState) {
getTileAt(x, y).setFlag(flagState);
}
Best Answer
Yes, returning a reference to an element of a
std::vector
is safe, unless you change the number of elements in the container while holding on to the reference.Whether it is a good practice can be debated, but that is mostly for public functions, where returning a reference to internal data breaks encapsulation.
If you know that the size of the board is completely fixed, then returning a reference from a private function is perfectly fine.