c++ - boost::optional<T&> vs T*

标签 c++ boost boost-optional

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

相关文章:

c++ - 我已经编写了 C++ 代码来将 boost::optional 视为一个范围,但它无法编译

c++ - c++ 中的可选引用是否保留对象生命?

python - 使用 boost::python 包装 boost::optional

c++ - 永远不会终止的程序是有效的 C++ 程序吗?

c++ - 如何将 map 中的 copy_if 复制到 vector ?

python - boost::python 从 numpy.ndarray 返回值中提取 C++ 值

c++ - 只计算递增次数的输出迭代器?

c++ - 这段代码做了什么,为什么编译?

c++ - DEFPUSHBUTTON 不将焦点默认为 IDCANCEL

c++ - boost::operators 混合算术