2

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, vectors 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);
}
  • It depends on a lot of things. What's the lifetime of whatever is calling getTileAt vs what owns the board? Is it even possible that something will have saved references to the tiles, between whatever else is modifying the board? If your application is single threaded, it's easy to reason about when the Board is being accessed. Also, whether members are private vs public has no bearing on whether references "leak" or not. – whatsisname May 7 '15 at 23:07
  • Are you using c++11? – user22815 May 7 '15 at 23:43
  • Yes. I'll update the tag. I didn't think it would be relevant. – Carcigenicate May 7 '15 at 23:44
  • No need to remove the unversioned tag: Now there's no syntax-highlighting. Anyway, it makes lots of sense in some situation, and is obviously wrong in others. Not a bad practice in general. – Deduplicator May 8 '15 at 0:01
3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.