【问题标题】:returning an emptyObject instead of a reference to a vector返回一个空对象而不是对向量的引用
【发布时间】:2015-11-14 08:29:46
【问题描述】:

给出两个类 A 和 B,其中 B 的 uinque_ptr 为 A!

class B {
    unique_ptr<A> a;
    B() {
    }
    ~B() {
    }
}

A 有一个方法返回一个自己的 unique_ptr 向量,如下所示:

   vector<unique_ptr<A>> const& A::getObjects() const {
        return this->myVector;
    }

现在我想在 B 中实现一个方法,该方法检查 A 的 unique_ptr 是否已存在,否则返回 A 中的向量,否则将引用空向量或 Null 作为错误:

 vector<unique_ptr<A>> const& B::getObjects()const{
    if (this->a.get()!=nullptr){
       return this->a->getObjects()
    }
   //ToDo an empty object or null
 }

我的问题是我可以在上面的函数中返回什么?返回 nullptr 给出编译错误。返回以下代码:

向量结果; 返回结果;

会引发警告:引用局部变量结果返回[-Wreturn-local-addr]

并返回 {}(返回 {})给我另一个警告:

返回对临时 [-Wreturn-local-addr] 的引用

所以我的问题是我可以返回什么而不给出警告或错误?

【问题讨论】:

    标签: c++ c++11 null smart-pointers return-type


    【解决方案1】:

    所以我的问题是我可以返回什么而不给出警告或错误?

    你可以在你的函数中有一个static vector&lt;unique_ptr&lt;A&gt;&gt; nullresult;,并返回那个以防万一:

    vector<unique_ptr<A>> const& B::getObjects()const{
        static vector<unique_ptr<A>> nullresult;
        if (this->a.get()!=nullptr){
            return this->a->getObjects()
        }
        return nullresult;
     }
    

    【讨论】:

    • 谢谢!我搜索了一下。我认为抛出异常比使用静态向量更好。
    • @Govan 好吧,这当然是另一种选择。我刚刚回答了您具体询问的内容。
    猜你喜欢
    • 2021-01-11
    • 1970-01-01
    • 2023-01-04
    • 2019-06-05
    • 2013-12-29
    • 2010-09-13
    • 2020-04-08
    • 2011-08-03
    • 1970-01-01
    相关资源
    最近更新 更多