何时使用 boost::optional 以及何时使用 std::unique_ptr 在您想要实现一个可以返回“无"的函数的情况下? [英] When to use boost::optional and when to use std::unique_ptr in cases when you want to implement a function that can return "nothing"?

查看:14
本文介绍了何时使用 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 在您想要实现一个可以返回“无"的函数的情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆