ScopedHandle

来源:互联网 发布:淘宝匿名评价不显示吗 编辑:程序博客网 时间:2024/06/05 15:05

class ScopedHandle {

 public:

  ScopedHandle() : handle_(NULL) {

  }

 

  explicit ScopedHandle(HANDLE h) : handle_(NULL) {

    Set(h);

  }

 

  ~ScopedHandle() {

    Close();

  }

 

  // Use this instead of comparing to INVALID_HANDLE_VALUE to pick up our NULL

  // usage for errors.

  bool IsValid() const {

    return handle_ != NULL;

  }

 

  void Set(HANDLE new_handle) {

    Close();

 

    // Windows is inconsistent about invalid handles, so we always use NULL

    if (new_handle != INVALID_HANDLE_VALUE)

      handle_ = new_handle;

  }

 

  HANDLE Get() {

    return handle_;

  }

 

  operator HANDLE() { return handle_; }

 

  HANDLE Take() {

    // transfers ownership away from this object

    HANDLE h = handle_;

    handle_ = NULL;

    return h;

  }

 

  void Close() {

    if (handle_) {

      if (!::CloseHandle(handle_)) {

        NOTREACHED();

      }

      handle_ = NULL;

    }

  }

 

 private:

  HANDLE handle_;

  DISALLOW_EVIL_CONSTRUCTORS(ScopedHandle);

};

原创粉丝点击