问题描述
据我所知,有 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 在您想要实现一个可以返回“无"的函数的情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)