推动::可选< T&安培;> VS T * [英] boost::optional<T&> vs T*

查看:234
本文介绍了推动::可选< T&安培;> VS T *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想明白的时候是使用一些附带升压并有关于使用的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 *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆