对于一个简单的游戏,我有这个类,它检查游戏实体前面是否有任何对象。
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文件)编译和运行代码时,一切都很好,没有分段错误或任何其他类型的错误。我不知道是什么导致了这种行为…
发布于 2015-07-12 22:39:36
旧的,但是:bus指的是Game的静态成员吗?看起来是这样的。如果是这样的话,您将容易受到"static initialisation order fiasco“的影响,即不同的.cpp文件可能会实例化自己的静态变量,与试图访问它们的其他对象相比,可能是在它们准备好之前,它们的顺序是无序的。
消息来源:它刚刚发生在我身上。我有一个静态常量数据集,以及一个指向该数据的静态指针容器。在不同的翻译单元中定义它们导致了一个模糊的段错误,原则上我可以理解,但我不会浪费时间试图找出确切的机械原因。因此,我将有问题的实例化移动到一个单独的cpp文件中,将它们按正确的依赖顺序放入其中,然后一切都恢复正常。
https://stackoverflow.com/questions/26443708
复制相似问题