我试图了解何时才是使用boost
附带的某些结构的恰当时机,并且对于将boost::optional
与引用一起使用存在疑问。
假设我有以下使用boost::optional
的类:
class MyClass {
public:
MyClass() {}
initialise(Helper& helper) {
this->helper = helper;
}
boost::optional<Helper&> getHelper() {
return helper;
}
private:
boost::optional<Helper&> helper;
}
我为什么要使用以上内容代替:
class MyClass {
public:
MyClass() : helper(nullptr) {}
initialise(Helper& helper) {
this->helper = &helper;
}
Helper* getHelper() {
return helper;
}
private:
Helper* helper;
}
它们都传达了相同的意图,即
getHelper
可以返回null
,并且调用方仍然需要测试是否返回了帮助程序。如果您需要知道'a value',
boost::optional
和'not a value'之间的区别,应该只使用nullptr
吗? 最佳答案
与原始指针相比,可选引用可能建议(1)不使用指针算法,并且(2)引用对象的所有权保留在其他位置(因此delete
显然不会与变量一起使用)。
关于c++ - boost::optional <T&> vs T *,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17007949/