C++ std::unique_ptr return 来自函数并测试 null

C++ std::unique_ptr return from function and test for null

我有一个函数需要 return 指向 class myClass 对象的指针。为此,我使用 std::unique_ptr.

如果函数成功,它将return一个指向包含数据的对象的指针。如果失败,应该 return null.

这是我的代码框架:

std::unique_ptr<myClass> getData()
{
   if (dataExists)
      ... create a new myClass object, populate and return it ...

   // No data found
   return std::unique_ptr<myClass> (null); // <--- Possible?
}

main 上:

main()
{
   std::unique_ptr<myClass> returnedData;

   returnedData = getData();

   if (returnedData != null)  // <-- How to test for null?
   {
      cout << "No data returned." << endl;
      return 0;
   }

   // Process data
}

所以我的问题是:

a) 是否可以使用 std::unique_ptr 完成(return 对象或 null)?

b) 如果可以的话,如何实现?

c) 如果不可能,有什么替代方案?

感谢您的帮助。

是的,这是可能的。一个默认构造的unique_ptr就是你想要的:

Constructs a std::unique_ptr that owns nothing.

// No data found
return std::unique_ptr<myClass>{};

相当于nullptr_t构造函数,所以也许这样更清楚:

// No data found
return nullptr;

以下任一方法都有效:

return std::unique_ptr<myClass>{};
return std::unique_ptr<myClass>(nullptr);

要测试返回的对象是否指向有效对象,只需使用:

if ( returnedData )
{
   // ...
}

参见http://en.cppreference.com/w/cpp/memory/unique_ptr/operator_bool

是的,这是可能的。默认构造的 unique_ptr 或从 nullptr 构造的可以被视为 null:

std::unique_ptr<MyClass> getData()
{
    if (dataExists)
        return std::make_unique<MyClass>();
    return nullptr;
}

要测试 null,要么与 nullptr 进行比较,要么利用转换为 bool:

int main()
{
    std::unique_ptr<MyClass> returnedData = getData();

    if (returnedData)
    {
        ... 
    }
}

在最新的 C++ 库中,<memory> 中应该有一个 make_unique 函数,使我们能够像 C++11 库中允许的那样轻松地创建 unique_ptr make_shared 和共享指针。

因此您可以通过返回 std::make_unique(nullptr)

来稍微阐明代码

此外,在下一个版本的 C++ 中,将有一个 "option" 类型,它的计算结果为 some 值或 none 值。 none 值不允许被视为有效值,不像空 unique_ptr 可以被视为 nullptr。选项类型将代表进入标准库的另一个 Boost。