简体   繁体   中英

Adding A Pointer To A Class Instance From The End Of One Vector To Another

So in the program there is a vector called called cardDeck which contains multiple pointers to instances of a class called Card:

std::vector<Card*> cardDeck;                                

Likewise there is a second vector called charCards also containing multiple pointers to instances of a class called card:

std::vector<Card*> charCards;                              

Part of the program functionality is to add the pointer to the card class instance from the end of the cardDeck vector to the end of the charCards vector:

charCards.push_back(cardDeck.back());                                                                               //Add the card selected from the deck to the Player's vector of initialisation cards

So for example if you start with the first card:

在此处输入图片说明

And then add a second card, instead of displaying the first card aligned with the second like so which is what SHOULD happen:

在此处输入图片说明

Instead only the second card (ie. the most recent card added to the vector) is rendered to the screen:

在此处输入图片说明

The question is - why do the sprites belonging to the card class instances preceeding the last instance in the charCards vector stop rendering when a new one is added?

Somewhere, in code you're not showing us, you're creating a pointer to a local variable, and pushing that pointer into the container. Then, you're doing it again. And again.

Thing is, those are all dangling pointers, and they probably even contain the same address (though this is not guaranteed). That's why you're seeing the same values "in" every element.

  • Don't store pointers, or
  • Don't store dangling pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM