我试图了解何时才是使用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/

10-09 06:36
查看更多