【发布时间】:2012-06-15 21:26:38
【问题描述】:
我有一个指针列表,这些指针引用了我的游戏中需要转弯的时间对象。此示例在列表中有两个 TimeObject*。此代码一直有效,直到从列表中删除一个项目:当发生这种情况时,另一个指向的地址将变为无效地址。发生这种情况时,TimeObject 都不会被删除;只有指针从列表中删除。这是什么原因造成的?
TimeUnlink() 在TimeObject::Tick() 中被调用。它不是静态的,但列表是。
我在 Linux 上使用 GCC 4.6.2。程序没有线程化。
void TimeObject::TimeUnlink()
{
printf("Time unlink\n");
TimeObject::list_.remove(this);
timeobject_flags_.linked_ = 0;
}
void GameTime::GameTurn(uint16_t _time)
{
tick_ += _time;
for(std::list<TimeObject*>::iterator it = TimeObject::list_.begin(); it != TimeObject::list_.end(); ++it)
{
TimeObject *timeobject = *it;
printf("GameTurn %p\n", timeobject);
if(timeobject == NULL) { printf("continue\n"); continue; }
timeobject->time_ += _time;
if(timeobject->speed_ && timeobject->time_ >= timeobject->speed_)
{
while(timeobject->timeobject_flags_.linked_ && timeobject->time_ - timeobject->speed_ > 0)
{
timeobject->time_ -= timeobject->speed_;
if(timeobject->mapobject_)
{
timeobject->mapobject_->Tick();
}
}
}
}
}
错误输出:
GameTurn 0xc1e048
GameTurn 0x696828
GameTurn 0xc1e048
GameTurn 0x696828
GameTurn 0xc1e048
GameTurn 0x696828
GameTurn 0xc1e048
Time unlink
GameTurn (nil)
continue
GameTurn 0xc1e030
Program received signal SIGSEGV, Segmentation fault.
0x00000000004059a1 in GameTime::GameTurn(unsigned short) ()
【问题讨论】:
-
是否有多个线程访问和修改
list_? -
TimeUnlink 函数在哪里被调用?这个函数或列表是静态成员吗?
-
TimeUnlink()在TimeObject::Tick()期间被调用 -
可以显示Tick函数吗??
-
顺便说一句,在您的容器中使用智能指针(或根本不使用指针)。因为您使用指针,您需要手动释放每个项目(即调用
delete),从而使容器无法为您管理内存。
标签: c++ pointers segmentation-fault stdlist