我有一个指针列表作为类的成员。我实例化该类,当列表为空时,各种函数(如size()和empty())会失败并出现段错误。当我在列表中添加内容时,它们很好。我试图用测试文件来抽象我正在做的事情,它完美地工作。这就是我认为我的代码失败时所做的事情(虽然显然不是):
#include <list>
#include <iostream>
class Test {
int i;
};
int main() {
std::list<Test*> tlist;
if (tlist.empty()) {
std::cout << "List empty";
} else {
std::cout << "List not empty";
}
}
我无法发布造成问题的整个代码清单,因为它相当大并且在一堆文件上,但会尝试直接从代码粘贴所有相关位:
player.h中的类声明:
class Player : public ScreenObject {
private:
std::list<Thing*> inventory;
构造函数中没有对该列表进行任何操作。
失败的地方:
main.cpp中:
Player pc(iname, w_choice, c_choice, 11, 11, WHITE, '@');
...
if (pc.addToInv(t)) {
currentLevel.delObject(id);
}
...
player.cpp:
int Player::addToInv(Thing& t) {
if (inventory.size() <= 52) {
inventory.push_back(&t);
} else {
shiplog("Cannot add to inventory, 52 item limit reached",10);
return 0;
}
}
使用gdb运行时出现的错误发生在对size()的调用上,最终在这里结束:
Program received signal SIGSEGV, Segmentation fault.
0x0804eda6 in std::_List_const_iterator<Thing*>::operator++ (this=0xbfff9500)
at /usr/include/c++/4.4/bits/stl_list.h:223
223 _M_node = _M_node->_M_next;
任何猜测都非常感激!
完全回溯是:
(gdb) bt
0 0x0804e28a in std::_List_const_iterator<Thing*>::operator++ (
this=0xbfff9500) at /usr/include/c++/4.4/bits/stl_list.h:223
1 0x0804e64e in std::__distance<std::_List_const_iterator<Thing*> > (
__first=..., __last=...)
at /usr/include/c++/4.4/bits/stl_iterator_base_funcs.h:79
2 0x0804e4d3 in std::distance<std::_List_const_iterator<Thing*> > (
__first=..., __last=...)
at /usr/include/c++/4.4/bits/stl_iterator_base_funcs.h:114
3 0x0804e2e6 in std::list<Thing*, std::allocator<Thing*> >::size (
this=0xbffff244) at /usr/include/c++/4.4/bits/stl_list.h:805
4 0x0804df78 in Player::addToInv (this=0xbffff068, t=...) at player.cpp:551
5 0x0804a873 in main (argc=1, argv=0xbffff494) at main.cpp:182
答案 0 :(得分:1)
int Player::addToInv(Thing& t) {
if (inventory.size() <= 52) {
inventory.push_back(&t);
} else {
shiplog("Cannot add to inventory, 52 item limit reached",10);
return 0;
}
}
Thing 通过引用传递,但随后将其地址传递给inventory.push_back()。试着传递't'。