stout代码分析之三:Option类

  为了安全表示NULL, stout实现了Option类。Option对象有两种状态:

enum State {
    SOME,
    NONE,
  };

  其中SOME表示非空,NONE表示为空。可通过isSome和isNone判断Option对象是否为空。

  Option类符合RAII的特性,构造函数和析构函数如下:

Option(const Option<T>& that)
  {
    state = that.state;
    if (that.t != NULL) {
      t = new T(*that.t);
    } else {
      t = NULL;
    }
  }

  注意 Option类似于boost::unique_ptr, 不同Option对象之间不会共享内存。以下是Option的使用示例:

  

#include "stout/option.hpp"
#include <iostream>

int main()
{
  Option<int> a;
  std::cout << (a.isSome() ? "isSome" : "isNone") << std::endl;

  Option<int> b(100);
  std::cout << (b.isSome() ? "isSome" : "isNone") << std::endl;

  auto c = Option<int>::none();
  std::cout << (c.isSome() ? "isSome" : "isNone") << std::endl;

  auto d = Option<int>::some(10);
  std::cout << (d.isSome() ? "isSome" : "isNone") << std::endl;

  std::cout << ( a == c ? "a equals c" : "a not equal c") << std::endl;

  d = b;
  std::cout << ( b == d ? "b equals d" : "b not equal d") << std::endl;

  std::cout << a.get() << std::endl;
  std::cout << b.get() << std::endl;
  return 0;
}

 

posted @ 2016-09-17 20:04  后端技术小屋  阅读(352)  评论(0编辑  收藏  举报