C++ std::unique_ptr 从函数返回并测试空值

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

本文关键字:返回 测试 函数 空值 ptr std unique C++      更新时间:2023-10-16

我有一个函数需要返回指向类myClass对象的指针。为此,我正在使用std::unique_ptr.

如果函数成功,它将返回指向包含数据的对象的指针。如果失败,则应返回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完成(返回对象或null(吗?

b( 如果可能,如何实施?

c( 如果不可能,还有什么选择?

感谢您的帮助。

以下任一方法都可以:

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是您想要的:

构造一个一无所有std::unique_ptr

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

这等效于 nullptr_t 构造函数,所以也许这更清楚:

// No data found
return nullptr;

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

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_ptrmake_shared和共享指针。

因此,您可以通过返回std::make_unique(nullptr)来阐明代码

另外,在C++的下一个版本中,将有一个"选项"类型,其评估值为some值或none值。不允许将none值视为有效值,这与空unique_ptr可以被视为 nullptr 不同。选项类型将代表进入标准库的另一块 Boost。