当使用boost ::可选的,使用std ::案件的unique_ptr当你想实现一个可以返回&QUOT功能;没有什么"? [英] 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"?
问题描述
据我所知有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,配对一个布尔标志和异常时,发现没有一个版本
*- 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();
那么,有没有任何理由prefere一个比其他?
So are there any reasons to prefere one over the other?
推荐答案
这取决于:你是否想返回的处理的或的复制的
It depends: do you wish to return a handle or a copy.
如果您想返回的处理的:
-
人*
-
的boost ::可选&LT;&人放;&GT;
Person*
boost::optional<Person&>
都可以接受的选择。我倾向于使用 PTR&LT;人方式&gt;
类抛出的空访问情况,但是这是我的偏执
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 ::可选&LT;&人GT;
非多态类 -
的std ::的unique_ptr&LT;&人GT;
多态类
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 ::可选的,使用std ::案件的unique_ptr当你想实现一个可以返回&QUOT功能;没有什么&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!