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 在您想要实现一个可以返回“无"的函数的情况下?
基础教程推荐
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
