Help with STL and objects

I'm trying to make a program that plays a card game. I currently have a function that returns a card object pointer. This works perfectly. I am able to use that card pointer fine. The problem is that when I put that card pointer into a vector or list, and try to access the pointer subsequently, I get back gibberish.

I assume that I'm not assigning the pointer correctly in the list or I'm not accessing it correctly, but I don't know how the fix either. Please help:

1
2
3
4
5
6
7
8
9
10
11
12
list <card *> get_cards_from_turn()
{
	card * c; 	
	list <card *> hand;
	c = taking_turns();
	cout << "get_cards 1: " << c->get_suit() << endl;
	hand.push_front(c);
	if (hand.empty())
		cout << "EMPTY";
	cout << "get_cards 2: "<< hand.front()->get_suit() << endl;
	return hand;
}


The output from this code is:
get_cards 1: h
get_cards 2: +

** the h is for hearts.
You are doing both correctly.

I suspect the problem is that you do not have valid memory for this card. Does taking_turns returned a new'd card? Can you post taking_turns?

EDIT:

in fact I'm sure that's the problem. You must be returning a pointer to a local object. push_front is modifying the stack, thereby corrupting your 'card'


The easy solution here is to just not use pointers. Just return a full card object, put a full card in the list, etc, etc. No need for pointers here.
Last edited on
Ok I'll change it to use the card object instead. Thank you for your help.
Topic archived. No new replies allowed.