【问题标题】:C++, What to return from a function with reference return type to indicate errorC++,从具有引用返回类型的函数返回什么以指示错误
【发布时间】:2015-03-20 09:26:45
【问题描述】:

假设我们有一个类

class cFoo {};

另一个带有cFoo对象的向量,像这样:

class cContainer
    {
        public:
            const cFoo& getFoo(std::size_t index) const;
        private:
            std::vector<cFoo> fooList_;
    }
    const fCoo& cContainer::getfoo(std::size_t index) const
    {
        if(index < fooList_.size())
            return fooList_[index];
        else
            ??????????
    };

所以我的问题是“在这种情况下,最佳做法是什么?”。那就是在 else 部分之后放置的内容来代替 ????s。这个问题对于返回引用的任何成员函数都有效(无论是否为 const)。当我们没有任何东西可以返回时,应该返回什么?

显然返回一个局部临时变量是没有问题的。我想到的另一个解决方案是返回cFoo() 的静态实例,最有可能在cFoo 类定义/实现期间定义和初始化。

当然,在这种情况下我们可以避免返回引用,但这可能会导致选择性能不佳(尤其是如果我们缺乏像移动运算符这样的好东西)。

【问题讨论】:

  • 选项类型在这里是完美的。太糟糕了 C++ 不支持任何东西来正确使用它们。

标签: c++


【解决方案1】:

在这种情况下,STL 所做的就是抛出异常。

例如,您可以查看std::vector::at 成员函数:

http://en.cppreference.com/w/cpp/container/vector/at

如果您要求超出范围的内容,则会引发 std::out_of_range 异常


另一种选择是返回一个指针或其在此上下文中语义更明确的等效项,optional referenceboost::optional&lt;fCoo&amp;&gt;

如果“超出范围”的情况不是那么特殊并且应该不时发生,我会建议这样做。

最后,如果您认为这种情况不应该发生,除非是开发人员错误,您应该使用assertion

【讨论】:

【解决方案2】:

如果函数没有要返回的东西是正常的,那么它不应该返回引用。返回指针没有错:

const fCoo* cContainer::getfoo(std::size_t index) const
{
    if(index < fooList_.size())
        return fooList_[index];
    else
        return nullptr;
};

如果没有要返回的东西表示该函数有一些异常,那么它应该抛出一个异常:

const fCoo* cContainer::getfoo(std::size_t index) const
{
    if(index < fooList_.size())
        return fooList_[index];
    else
        throw std::invalid_argument("out of range");
};

【讨论】:

  • 另一种选择是返回对特殊静态“错误”对象的引用。
  • ITYM return nullptr;return 之后的 else 也是多余的。
  • @MattMcNabb 谢谢,已更正。当这个短而对称的时候,我可能会保留else。但你是对的,没有必要。
猜你喜欢
  • 2018-12-08
  • 2014-01-23
  • 1970-01-01
  • 2015-01-18
  • 2021-01-11
  • 1970-01-01
  • 2015-04-18
  • 2020-02-11
  • 1970-01-01
相关资源
最近更新 更多