Strange problem with std:.vector

Hello,

I'm writing a chess game with C++ and SDL2 and I have a strange problem with std::vector.

I have a ChessPiece class and I tried to store the players chess pieces in a std::vector and it doesnt work properly (wrong ChessPiece textures appear).

The strange thing is, when I use a std::deque instead of a std::vector, everything works as expected. I didnt change a single line of code apart from replacing std::vector with std::deque.

It actually tried it with every type of STL container and c-array and everything works except std::vector

I use the the push_back method to add objects like this:

chessPieces.push_back( ChessPiece( ChessPieceType::Pawn ) );

It's too much code to post everything here.

Is there anything about std::vector I don't know about?
Iterator/pointer invalidation, perhaps?

For example, given an iterator or pointer to an element of a vector v, calling v.push_back() would invalidate those pointers or iterators if the vector's capacity changes.
Iterator invalidation makes sense since vector is probably most susceptible. You could try reserving the space for the 32 pieces before pushing them onto the vector.
You guys are right. if I reserve the space before and initialize the objects afterwards, it works. I do not use pointers to the vector but the ChessPiece class stores a object which stores a pointer. Is there any way to prevent this otherwise?
I do not use pointers to the vector

It's not a pointer to the vector that would be a problem, but a pointer (or iterator) to the objects that the vector contains. When the vector needs to grow in size it may need to move all of the objects to newly allocated memory, in which case any pointers/iterators you have to the old locations are useless.

Once you've loaded your chessPieces vector, as long as you don't add or remove anything from it, then your pointers/iterators will remain valid.

the ChessPiece class stores a object which stores a pointer

A pointer to what? A pointer to it's location in the vector? If so, then as long as you no longer modify the vector it should be okay.
Last edited on
The ChessPiece class contains a Texture object which contains a SDL_Texture* texture. This texture points to a SDL_Texture obtained from the function SDL_CreateTextureFromSurface ( https://wiki.libsdl.org/SDL_CreateTextureFromSurface ). Since I dont use any other pointer or iterator in this class, it has to be a problem with the SDL library.

I came up with a solution in which I just use a vector of shared_ptr<ChessPiece>. I think the pointer becomes invalid with the copy constructor.
Last edited on
If you are still having problems you need to make your code available so we can see exactly what's going on. You can upload it as a zip file somewhere and provide a link.
I will upload the project on github soon anyway, thanks for the help.
Topic archived. No new replies allowed.