如何处理用户造成的未定义行为

时间:2017-07-29 16:03:05

标签: c++ error-handling exception-handling

我有一个查找方法,它接受一个字符串(标签)向量,搜索对象向量,如果参数标签与对象的标签匹配,则返回指向对象的指针。如果用户指定的结果不匹配,我只返回一个nullptr:

Entity* Scene::findEntity(std::vector<std::string> tags)
{
    int matchIndex = findMatchIndex(tags);
    if (tags.size()  == 0 || matchIndex == -1) {
        std::string msg = "No entity with tag(s): " + formatTags(tags) + " found.";
        printf(msg.c_str());
        return nullptr;
    }
    else {
        return &_entities.at(matchIndex);
    }
}

例如,假设用户尝试这样做:

TestScene::TestScene()
{
    Entity player = Entity({ "player" }, { new Drawable(), new Transform(), new Collidable(), new PlayerScript() });

    spawnEntity(player);

    Entity* testPlayer = findEntity({ "Plsdfsdfdsfayer" });
    testPlayer -> getTags();
}

这将导致未定义的行为,因为findEntity返回nullptr。

什么是没有找到对象时处理的好方法?当用户尝试与nullptr交互时,我是否应该以程序方式崩溃以防止未定义的行为?因为没有找到对象而退出感觉有点过分......

0 个答案:

没有答案
相关问题