scoped_co_mem.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (c) 2011 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. #ifndef BASE_WIN_SCOPED_CO_MEM_H_
  5. #define BASE_WIN_SCOPED_CO_MEM_H_
  6. #include <objbase.h>
  7. #include "base/check.h"
  8. #include "base/macros.h"
  9. namespace base {
  10. namespace win {
  11. // Simple scoped memory releaser class for COM allocated memory.
  12. // Example:
  13. // base::win::ScopedCoMem<ITEMIDLIST> file_item;
  14. // SHGetSomeInfo(&file_item, ...);
  15. // ...
  16. // return; <-- memory released
  17. template <typename T>
  18. class ScopedCoMem {
  19. public:
  20. ScopedCoMem() : mem_ptr_(nullptr) {}
  21. ~ScopedCoMem() { Reset(nullptr); }
  22. T** operator&() { // NOLINT
  23. DCHECK(mem_ptr_ == nullptr); // To catch memory leaks.
  24. return &mem_ptr_;
  25. }
  26. operator T*() { return mem_ptr_; }
  27. T* operator->() {
  28. DCHECK(mem_ptr_ != NULL);
  29. return mem_ptr_;
  30. }
  31. const T* operator->() const {
  32. DCHECK(mem_ptr_ != NULL);
  33. return mem_ptr_;
  34. }
  35. void Reset(T* ptr) {
  36. if (mem_ptr_)
  37. CoTaskMemFree(mem_ptr_);
  38. mem_ptr_ = ptr;
  39. }
  40. T* get() const { return mem_ptr_; }
  41. private:
  42. T* mem_ptr_;
  43. DISALLOW_COPY_AND_ASSIGN(ScopedCoMem);
  44. };
  45. } // namespace win
  46. } // namespace base
  47. #endif // BASE_WIN_SCOPED_CO_MEM_H_