问题描述
我想明白的时候是使用一些附带升压
并有关于使用的boost ::可选的与参考。
I'm trying to understand when is the right time to use some of the structures that come with boost
and had a question regarding the use of boost::optional
with a reference.
假设我有下面的类,使用的boost ::可选的
:
Suppose I have the following class, using boost::optional
:
class MyClass {
public:
MyClass() {}
initialise(Helper& helper) {
this->helper = helper;
}
boost::optional<Helper&> getHelper() {
return helper;
}
private:
boost::optional<Helper&> helper;
}
为什么要使用上面,而不是:
Why would I use the above instead of:
class MyClass {
public:
MyClass() : helper(nullptr) {}
initialise(Helper& helper) {
this->helper = &helper;
}
Helper* getHelper() {
return helper;
}
private:
Helper* helper;
}
他们都传达相同的意图,即该调用getHelper
可以返回空
,调用者仍然需要测试如果一个辅助返回。
They both convey the same intent, i.e. that getHelper
could return null
, and the caller still needs to test if a helper was returned.
如果你只使用的boost ::可选的
如果你需要知道'值'之间的区别, nullptr
和'不'值?
Should you only be using boost::optional
if you need to know the difference between 'a value', nullptr
and 'not a value'?
推荐答案
相比于原始指针,任选的参考可以建议(1)指针运算不使用,和(2)所指的所有权别处维持(所以删除
显然无法与变量使用)。
Compared to a raw pointer, an optional reference may suggest that (1) pointer arithmetic is not used, and (2) ownership of the referent is maintained elsewhere (so delete
will clearly not be used with the variable).
这篇关于推动::可选&LT; T&安培;&GT; VS T *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!