何时使用 boost::optional 以及何时使用 std::unique_ptr 在您想要实现一个可以返回“无&q

2023-07-19C/C++开发问题
2

本文介绍了何时使用 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 classes
  • std::unique_ptr<Person> for polymorphic classes

因为动态分配会产生开销,所以您只在必要时使用它.

because dynamic allocation incurs an overhead, so you only use it when necessary.

这篇关于何时使用 boost::optional 以及何时使用 std::unique_ptr 在您想要实现一个可以返回“无"的函数的情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6