• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2011 The Chromium Authors
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_CO_MEM_H_
6 #define BASE_WIN_SCOPED_CO_MEM_H_
7 
8 #include <objbase.h>
9 
10 #include <utility>
11 
12 #include "base/check.h"
13 #include "base/memory/raw_ptr_exclusion.h"
14 
15 namespace base {
16 namespace win {
17 
18 // Simple scoped memory releaser class for COM allocated memory.
19 // Example:
20 //   base::win::ScopedCoMem<ITEMIDLIST> file_item;
21 //   SHGetSomeInfo(&file_item, ...);
22 //   ...
23 //   return;  <-- memory released
24 template <typename T>
25 class ScopedCoMem {
26  public:
ScopedCoMem()27   ScopedCoMem() : mem_ptr_(nullptr) {}
28 
29   ScopedCoMem(const ScopedCoMem&) = delete;
30   ScopedCoMem& operator=(const ScopedCoMem&) = delete;
31 
ScopedCoMem(ScopedCoMem && other)32   ScopedCoMem(ScopedCoMem&& other)
33       : mem_ptr_(std::exchange(other.mem_ptr_, nullptr)) {}
34   ScopedCoMem& operator=(ScopedCoMem&& other) {
35     Reset(std::exchange(other.mem_ptr_, nullptr));
36     return *this;
37   }
38 
~ScopedCoMem()39   ~ScopedCoMem() { Reset(nullptr); }
40 
41   T** operator&() {               // NOLINT
42     DCHECK(mem_ptr_ == nullptr);  // To catch memory leaks.
43     return &mem_ptr_;
44   }
45 
46   operator T*() { return mem_ptr_; }
47 
48   T* operator->() {
49     DCHECK(mem_ptr_ != NULL);
50     return mem_ptr_;
51   }
52 
53   const T* operator->() const {
54     DCHECK(mem_ptr_ != NULL);
55     return mem_ptr_;
56   }
57 
Reset(T * ptr)58   void Reset(T* ptr) {
59     if (mem_ptr_)
60       CoTaskMemFree(mem_ptr_);
61     mem_ptr_ = ptr;
62   }
63 
get()64   T* get() const { return mem_ptr_; }
65 
66  private:
67   // RAW_PTR_EXCLUSION: #addr-of, #union
68   RAW_PTR_EXCLUSION T* mem_ptr_;
69 };
70 
71 }  // namespace win
72 }  // namespace base
73 
74 #endif  // BASE_WIN_SCOPED_CO_MEM_H_
75