scoped_handle.h revision 731df977c0511bca2206b5f333555b1205ff1f43
1// Copyright (c) 2010 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_WIN_SCOPED_HANDLE_H_
6#define BASE_WIN_SCOPED_HANDLE_H_
7#pragma once
8
9#include <windows.h>
10
11#include "base/basictypes.h"
12#include "base/logging.h"
13
14namespace base {
15namespace win {
16
17// Used so we always remember to close the handle.
18// The class interface matches that of ScopedStdioHandle in  addition to an
19// IsValid() method since invalid handles on windows can be either NULL or
20// INVALID_HANDLE_VALUE (-1).
21//
22// Example:
23//   ScopedHandle hfile(CreateFile(...));
24//   if (!hfile.Get())
25//     ...process error
26//   ReadFile(hfile.Get(), ...);
27//
28// To sqirrel the handle away somewhere else:
29//   secret_handle_ = hfile.Take();
30//
31// To explicitly close the handle:
32//   hfile.Close();
33class ScopedHandle {
34 public:
35  ScopedHandle() : handle_(NULL) {
36  }
37
38  explicit ScopedHandle(HANDLE h) : handle_(NULL) {
39    Set(h);
40  }
41
42  ~ScopedHandle() {
43    Close();
44  }
45
46  // Use this instead of comparing to INVALID_HANDLE_VALUE to pick up our NULL
47  // usage for errors.
48  bool IsValid() const {
49    return handle_ != NULL;
50  }
51
52  void Set(HANDLE new_handle) {
53    Close();
54
55    // Windows is inconsistent about invalid handles, so we always use NULL
56    if (new_handle != INVALID_HANDLE_VALUE)
57      handle_ = new_handle;
58  }
59
60  HANDLE Get() {
61    return handle_;
62  }
63
64  operator HANDLE() { return handle_; }
65
66  HANDLE Take() {
67    // transfers ownership away from this object
68    HANDLE h = handle_;
69    handle_ = NULL;
70    return h;
71  }
72
73  void Close() {
74    if (handle_) {
75      if (!::CloseHandle(handle_)) {
76        NOTREACHED();
77      }
78      handle_ = NULL;
79    }
80  }
81
82 private:
83  HANDLE handle_;
84  DISALLOW_COPY_AND_ASSIGN(ScopedHandle);
85};
86
87}  // namespace win
88}  // namespace base
89
90#endif  // BASE_SCOPED_HANDLE_WIN_H_
91