對於一個簡單的遊戲,我有這個類,它檢查遊戲實體前面是否有任何對象。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文件)一切正常運行的代碼,不存在分段錯誤或任何其他類型的錯誤。我不知道是什麼導致此行爲...
猜測,你的代碼在其他地方有問題。檢查緩衝區溢出和內存使用情況 – 2014-10-19 11:21:23