我有一个函数与以下声明:
void playCard(string card);
Run Code Online (Sandbox Code Playgroud)
以及以下实施:
void Player::playCard(string card)
{
cout << "Playing " << card << "!" << endl;
// Find iterator representing the card to be played
vector<Card*>::iterator iter;
for(iter = hand.begin(); iter != hand.end(); iter++)
{
if( (*iter)->getName() == card)
continue;
}
// ERROR - Card not found in hand
if(iter == hand.end())
assert(false);
// more stuff
}
Run Code Online (Sandbox Code Playgroud)
该函数从以下代码块调用:
// Divide string into 2 words
istringstream iss(in, istringstream::in);
string command, target;
iss >> command >> target;
if(command == "play")
{
players.at(currentTurn)->playCard(target);
}
Run Code Online (Sandbox Code Playgroud)
球员被宣布为:
vector<Player*> players;
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,无论"卡"字符串是什么,我都会找到卡未找到的断言.根据gdb:
Breakpoint 1, Player::playCard (this=0xb3a010, card=0x28ca00) at Player.cpp:138
138 cout << "Playing " << card << "!" << endl;
(gdb) print card
$1 = (string *) 0x28ca00
Run Code Online (Sandbox Code Playgroud)
因此在playCard()函数中,由于某种原因,card变量是一个指针.有趣的是,cout语句仍然正确显示字符串的内容.在调用playCard()之前,变量不是根据gdb的指针,只是一个普通的字符串.
此外,这很有趣:
(gdb) print iter
$1 = {_M_current = 0xb9a328}
(gdb) print iter->getName()
Couldn't find method __normal_iterator<Card**,std::vector<Card*, std::allocator<Card*> > >::getName
(gdb) print *iter
$2 = (class Card *&) @0xb9a328: 0xb9a160
(gdb) print *iter->getName()
Couldn't find method __normal_iterator<Card**,std::vector<Card*, std::allocator<Card*> > >::getName
(gdb) print (*iter)->getName()
Program received signal SIGSEGV, Segmentation fault.
0x61111178 in memcpy () from /usr/bin/cygwin1.dll
Run Code Online (Sandbox Code Playgroud)
因此,当我尝试打印出最后一个时,gdb会导致段错误,但是相同的代码在没有任何段错误的情况下执行.
我有一种感觉,我正在处理一些奇怪的内存问题,这些问题与一个充满指向对象的向量有关,但我不能完全指责它.
这里发生了什么?