我试图了解何时是使用 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”、nullptr
和“not a value”之间的区别,您是否应该只使用 boost::optional
?
最佳答案
与原始指针相比,可选引用可能表明 (1) 不使用指针算法,以及 (2) 在其他地方维护所指对象的所有权(因此显然不会使用 delete
与变量)。
关于c++ - boost::optional<T&> vs T*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17007949/