C++:分离标题和实现文件(.hpp/.cpp)时出现分段错误
问题描述:
对于一个简单的游戏,我有这个类,它检查游戏实体前面是否有任何对象。C++:分离标题和实现文件(.hpp/.cpp)时出现分段错误
class FieldOfView : public anax::System<FieldOfView>
{
public:
FieldOfView() :
Base(anax::ComponentFilter().requires<components::Transform, components::FieldOfView>())
{
}
void update()
{
using std::find;
using std::begin;
using std::end;
using std::remove_if;
auto& bus = Game::get().getMessageBus();
for (auto& entity : getEntities())
{
auto collisions = getCollisions(entity);
auto& inSight = entity.getComponent<components::FieldOfView>().inSight;
for (auto& collided : collisions)
{
if (find(begin(inSight), end(inSight), collided) == end(inSight))
{
inSight.push_back(collided);
bus.send<message::EntityEnteredFov>(entity, collided);
}
}
std::function<bool(const anax::Entity&)> hasCollided = [&collisions](const anax::Entity& x) -> bool {
return find(begin(collisions), end(collisions), x) != end(collisions);
};
for (const auto& seenEntity : inSight)
{
if (!hasCollided(seenEntity))
bus.send<message::EntityLeftFov>(entity, seenEntity);
}
inSight.erase(remove_if(begin(inSight), end(inSight), std::not1(hasCollided)), end(inSight));
}
}
};
该类位于文件“FieldOfView.hpp”中。它可以正常工作。不过,我想分开头文件和实现文件,所以我创建了一个“FieldOfView.cpp”。
void FieldOfView::update()
{
// the same code as above
}
我还更新了头文件( “FieldOfView.hpp”):因为段故障的
class FieldOfView : public anax::System<FieldOfView>
{
public:
FieldOfView() :
Base(anax::ComponentFilter().requires<components::Transform, components::FieldOfView>())
{
}
void update();
};
当该代码(HPP + CPP)运行时,该程序中止(Segmentation fault: 11
) 。在此行中出现的错误:
bus.send<message::EntityLeftFov>(entity, seenEntity);
当我编译和仅使用单一HPP(无CPP文件)一切正常运行的代码,不存在分段错误或任何其他类型的错误。我不知道是什么导致此行为...
答
旧的,但:bus
是指Game
的静态成员?它似乎。如果是这种情况,那么您应该对“static initialisation order fiasco”承担责任,因为不同的.cpp文件可能会实例化它们自己的静态变量,与其他试图访问它们的对象相比,它们可能在它们准备好之前失灵。
来源:它只是发生在我身上。我有一个静态const数据集,以及指向该数据的静态容器。在不同的翻译单元中定义这些内容导致模糊的段错误,我原则上理解,但不会浪费时间来试图找出确切的机制原因。所以,我将违规实例移动到一个单独的cpp文件中,并将它们按正确的依赖顺序排列,并且一切都很顺利。
猜测,你的代码在其他地方有问题。检查缓冲区溢出和内存使用情况 – 2014-10-19 11:21:23