When to use boost::optional and when to use std::unique_ptr in cases when you want to implement a function that can return quot;nothingquot;?(何时使用 boost::optional 以及何时使用 std::unique_ptr 在您想要实现一个可以返回“无的函数的情况下?)
问题描述
据我所知,有 2* 种方法可以实现有时不返回结果的函数(例如在 ppl 列表中找到的人).
From what I understand there are 2* ways you can implement a function that sometimes doesnt return a result(for example is person found in a list of ppl).
*- 我们忽略原始 ptr 版本,与 bool 标志配对,并在找不到版本时出现异常.
*- we ignore raw ptr version, pair with a bool flag, and exception when none found version.
boost::optional<Person> findPersonInList();
或
std::unique_ptr<Person> findPersonInList();
那么有什么理由更喜欢一个吗?
So are there any reasons to prefere one over the other?
推荐答案
这取决于:您希望返回句柄还是副本.
It depends: do you wish to return a handle or a copy.
如果你想返回一个句柄:
人*boost::optional
都是可以接受的选择.我倾向于使用 Ptr 类,它会在访问空值时抛出异常,但那是我的偏执.
are both acceptable choices. I tend to use a Ptr<Person> class which throws in case of null access, but that's my paranoia.
如果您希望返回副本:
boost::optional用于非多态类std::unique_ptr用于多态类
boost::optional<Person>for non polymorphic classesstd::unique_ptr<Person>for polymorphic classes
因为动态分配会产生开销,所以您只在必要时使用它.
because dynamic allocation incurs an overhead, so you only use it when necessary.
这篇关于何时使用 boost::optional 以及何时使用 std::unique_ptr 在您想要实现一个可以返回“无"的函数的情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:何时使用 boost::optional 以及何时使用 std::unique_ptr 在您想要实现一个可以返回“无"的函数的情况下?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
