C++ std::unique_ptr 从函数返回并测试空值
C++ std::unique_ptr return from function and test for null
我有一个函数需要返回指向类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_ptr
的make_shared
和共享指针。
因此,您可以通过返回std::make_unique(nullptr)
来阐明代码
另外,在C++的下一个版本中,将有一个"选项"类型,其评估值为some
值或none
值。不允许将none
值视为有效值,这与空unique_ptr可以被视为 nullptr 不同。选项类型将代表进入标准库的另一块 Boost。
- 我是否正确测试了返回值优化?
- 使用 Google 基准测试时返回值会发生什么情况?
- 测试用例状态为失败,但返回的值为 true
- 谷歌测试:如何返回成功结果?
- 为什么生成文件返回 g++: 错误: h 文件或目录 make: *** [生成文件:12: 测试] 错误 1?
- 谷歌嘲笑!我的测试出错.默认情况下,呼叫将返回调用
- 为什么这个测试总是返回假
- 单位测试QT中的非返回功能
- 使用C ,使用SFINAE测试静态成员的存在,返回错误的值
- 如何测试仅返回系统值的API
- Google Mock - 使用 CoTaskMemFree 时,测试返回没有结果
- 如何在调试版本中测试断言,但在发布中返回值
- 二进制搜索测试柜不返回值
- 返回语句中的条件测试
- 显式布尔操作员 - 无法返回,测试,初始化bool
- 将函数中的值返回到由 while 循环测试的值.C++
- 检查两个数组中的相似元素,为某些测试返回正确的值,为其他测试返回不正确的值
- 为什么我的线段交叉测试不返回 true?
- 为什么 WinDbg 在测试内存泄漏程序时总是返回相同的"!heap -s"信息?
- 为什么一位数组返回零?合并排序测试