什么是正确的样式来表明没有什么可返回的

What is the correct style to indicate that there is nothing to return?

本文关键字:什么 返回 样式      更新时间:2023-10-16

我使用 unordered_maps unordered_map存储对象:

std::unordered_map<int, std::unordered_map<int, WorldObject>> _worldObjects;

我使用此函数检索一个对象:

   WorldObject& objectAtLocation(int x,int y){
        if(_worldObjects.find(x)!=_worldObjects.end() && _worldObjects[x].find(y)!= _worldObjects[x].end()){
            //Contains an object
        }else{
            //Does not contain an object at that location. What should I return ?
        }
    }

如果在 x,y 处没有存储对象,那么在此函数中指示它的正确方法是什么?

例如,我可以像这样修改函数:

//return value indicating presence of object, output the variable that data is copied into.
bool objectAtlocation(int x,int y,WorldObject& output);

有什么建议吗?

编辑:只使用指针更好吗?

std::unordered_map<int, std::unordered_map<int, WorldObject*>> _worldObjects;

所以我可以做:

WorldObject* objectAtLocation(int x,int y){
    WorldObject* result = nullptr;
    if(_worldObjects.find(x)!=_worldObjects.end() && _worldObjects[x].find(y)!= _worldObjects[x].end()){
        //Contains an object
        result = _worldObjects[x][y];
    }else{
        //Does not contain an object at that location. Returning nullptr:
    }
    return result;
}

编辑:在坐标(x,y)处没有对象并不例外。因此,我不需要抛出异常。我只想指出,该地点什么都没有。

您能否提供带有答案的示例代码,因为我是C++新手,并且可能无法从您的评论中完全理解?

"标准C++方式"是返回迭代器。如果未找到与您的搜索条件匹配的内容,则返回_worldObjects.end()(编辑:这在您的情况下不起作用,我误读了您如何使用容器)

如果您的容器很复杂并且不适合返回迭代器,则可以返回指向对象的指针,如果未找到对象,则返回nullptr

编辑:

从您的问题编辑中改编代码示例:

WorldObject* objectAtLocation(int x,int y){
    WorldObject *result = nullptr;
    const auto xIter = _worldObjects.find(x)
    if(xIter !=_worldObjects.end()){
        const auto yIter = xIter->find(y);
        if (yIter != xIter->end()){
            //Contains an object
            result = &(*yIter);
        }
    }
    return result;
}

有几种方法可以做到这一点,在我看来,没有理由做一些过于复杂的事情。所以我认为你自己的建议很好。

否则,您可以返回一个指针,然后在找不到任何内容时检查然后返回 null。

或者,您可以实现一个可为 null 的类(可以是模板或您从中继承的类),该类允许您检查实例是否为 null 对象。

不过,您可以为对象定义一个表示 null 的"默认"状态,并且可以对此进行检查,因此只要您找不到任何内容,就可以返回对 null 对象的引用。空对象可以是静态的,也可以不是静态的。