C ++ - safety of accessing a vector element through pointers
In my C ++ project, I use vector
to store bundles struct
that contain several elements for a simple game (i.e.: tic-tac-toe, cocc, x
vs o
, etc.). i.e:
struct gameMove
{
int x;
int y;
int player;
int order;
};
Every time during one game, every time a player makes a move (ie, places a x
or o
), information is saved in vector
thru push_back()
to create an "undo" function that currently works as expected.
In some parts of my undo / redo logic, I use functions that traverse vector
, find a matching element, and return a pointer directly to that element.
Is it safe, if I manage it correctly vector
, to access it, NULL output all pointers to the elements vector
, or are there inherent risks? I'm worried that if I extend the game I'm planning to make vector
(i.e.: use the same code for the chess game I'm working on) and that gets too big and needs to be automatically reallocated, the pointers become invalid (i.e.: the whole list is being moved to a new contiguous block that can match all elements), or is there some type of smart pointer interface for vector
doing the same thing?
Thank.
source to share
You are correct: if the vector has to grow, the addresses in vector
will change (or if the vector shrinks, but most implementations vector
do not shrink without any effort from the programmer).
The immediate simple solution would be to return the index to the vector instead of the pointer. This, if it is in range, will always be the correct way to find a specific element. [And instead NULL
you could use, for example, -1
or 0xDEAD
]
source to share
Do you feel use std::stack
or std::list
? The stack can be attractive on purpose to simplify the "undo" functionality you are looking for (since the last step will always be the top of the stack). But with a linked structure, you don't have to worry about the indexing issue, although if you are memory-heavy this might not be the best option ...
source to share