2014-10-18 60 views
0

對於一個簡單的遊戲,我有這個類,它檢查遊戲實體前面是否有任何對象。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文件)一切正常運行的代碼,不存在分段錯誤或任何其他類型的錯誤。我不知道是什麼導致此行爲...

+0

猜測,你的代碼在其他地方有問題。檢查緩衝區溢出和內存使用情況 – 2014-10-19 11:21:23

回答

0

舊的,但:bus是指Game的靜態成員?它似乎。如果是這種情況,那麼您應該對「static initialisation order fiasco」承擔責任,因爲不同的.cpp文件可能會實例化它們自己的靜態變量,與其他試圖訪問它們的對象相比,它們可能在它們準備好之前失靈。

來源:它只是發生在我身上。我有一個靜態const數據集,以及指向該數據的靜態容器。在不同的翻譯單元中定義這些內容導致模糊的段錯誤,我原則上理解,但不會浪費時間來試圖找出確切的機制原因。所以,我將違規實例移動到一個單獨的cpp文件中,並將它們按正確的依賴順序排列,並且一切都很順利。