Reputation: 1838
I have the following code:
Card.h
:
#include <string>
using namespace std;
class Card
{
public:
Card(string name);
~Card() {};
string GetName();
private:
string Name;
};
Card.cpp
:
#include "Card.h"
using namespace std;
Card::Card(string name) {Name=name;};
string Card::GetName() {return Name;}
Deck.h
:
#include "Card.h"
#include <vector>
class Deck {
public:
Card& DrawCard();
void AddCardToDeck(Card& c);
Deck();
~Deck();
private:
std::vector <Card> cardsindeck;
};
Deck.cpp
:
#include "Deck.h"
#include <vector>
#include <iostream>
using namespace std;
Card& Deck::DrawCard() {
//cout << cardsindeck.back().GetName()<<" was drawn "<<endl;
Card &c = cardsindeck.back();
cout << c.GetName()<<" was drawn "<<endl;
cardsindeck.pop_back();
cout << c.GetName()<<" popped from deck "<<endl;
return c;
}
Deck::Deck()
{
}
Deck::~Deck()
{
}
void Deck::AddCardToDeck(Card& c) {
cardsindeck.push_back(c);
}
Player.h
:
#include "Deck.h"
#include <vector>
using namespace std;
class Player {
public:
void Beginning();
Player(Deck _deck);
~Player() {};
private:
vector <Card> cardsindeck;
Deck deck;
};
Player.cpp
:
#include "Player.h"
using namespace std;
Player::Player(Deck _deck)
{
this->deck = _deck;
}
void Player::Beginning()
{
Card& c = deck.DrawCard();
}
main.cpp
:
#include "Player.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
Deck aDeck;
vector <Card> aHand;
Card c=Card("THIS THIS GREAT PLAYER");
Card& c1 =c;
aDeck.AddCardToDeck(c1);
Player P = Player(aDeck);
P.Beginning();
return 0;
}
The output I get is:
THIS THIS GREAT PLAYER was drawn
�\IS GREAT PLAYER popped from deck
Why does the 2nd line have that weird chars in place of "THIS THIS" ?
Upvotes: 0
Views: 91
Reputation: 38267
You have undefined behavior in this function:
Card& Deck::DrawCard() {
// ...
Card &c = cardsindeck.back();
// ...
cardsindeck.pop_back();
cout << c.GetName()<<" popped from deck "<<endl;
return c;
}
First, you alias the last element of cardsindeck
with a reference called c
. This is fine, and access to its member function is fine, too. Then, you remove the element from the container with cardsindeck.pop_back();
. From the docs on std::vector::pop_back
, we see that
No iterators or references except for
back()
andend()
are invalidated.
And that's the issue here. You are having a reference to back()
, and that is invalidated. It must be - you are deleting the element in the vector that c
refers to from the container. Accessing its members then e.g. by GetName()
is UB, then.
You can easily fix the issue by copying the return value of cardsindeck.back()
like this:
Card c = cardsindeck.back();
// ^^ No reference. The last element is copied
cardsindeck.pop_back(); // Doens't affect the copied instance above
return c;
Note that this requires changing the signature of the member function to
Card Deck::DrawCard()
where the return value is no reference anymore.
Upvotes: 7