OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2016 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 CONTENT_BROWSER_OWNED_INTERFACE_H_ |
| 6 #define CONTENT_BROWSER_OWNED_INTERFACE_H_ |
| 7 |
| 8 #include <memory> |
| 9 |
| 10 #include "base/memory/ptr_util.h" |
| 11 #include "base/memory/ref_counted.h" |
| 12 |
| 13 namespace content { |
| 14 |
| 15 // Common base class for interface impls, allowing them to be stored in a |
| 16 // type-erased container for ownership management. |
| 17 class OwnedInterface { |
| 18 public: |
| 19 OwnedInterface() = default; |
| 20 virtual ~OwnedInterface() = default; |
| 21 }; |
| 22 |
| 23 template <typename InterfaceImpl> |
| 24 class DeleteOnTaskRunner { |
| 25 public: |
| 26 DeleteOnTaskRunner( |
| 27 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner = nullptr) |
| 28 : task_runner_(task_runner) {} |
| 29 void operator()(const InterfaceImpl* impl) { |
| 30 if (task_runner_) { |
| 31 if (!task_runner_->DeleteSoon(FROM_HERE, impl)) { |
| 32 #if defined(UNIT_TEST) |
| 33 // Only logged under unit testing because leaks at shutdown |
| 34 // are acceptable under normal circumstances. |
| 35 LOG(ERROR) << "DeleteSoon failed on thread"; |
| 36 #endif // UNIT_TEST |
| 37 } |
| 38 } else { |
| 39 delete impl; |
| 40 } |
| 41 } |
| 42 ~DeleteOnTaskRunner() = default; |
| 43 |
| 44 private: |
| 45 const scoped_refptr<base::SingleThreadTaskRunner> task_runner_; |
| 46 }; |
| 47 |
| 48 template <typename InterfaceImpl> |
| 49 class OwnedInterfaceImpl : public OwnedInterface { |
| 50 public: |
| 51 OwnedInterfaceImpl( |
| 52 std::unique_ptr<InterfaceImpl> impl, |
| 53 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner = nullptr) |
| 54 : impl_(impl.release(), DeleteOnTaskRunner<InterfaceImpl>(task_runner)) {} |
| 55 |
| 56 ~OwnedInterfaceImpl() = default; |
| 57 |
| 58 // The returned pointer is owned by this object, which must outlive it. |
| 59 InterfaceImpl* get() { return impl_.get(); } |
| 60 |
| 61 private: |
| 62 std::unique_ptr<InterfaceImpl, DeleteOnTaskRunner<InterfaceImpl>> impl_; |
| 63 |
| 64 DISALLOW_COPY_AND_ASSIGN(OwnedInterfaceImpl); |
| 65 }; |
| 66 |
| 67 } // namespace content |
| 68 |
| 69 #endif // CONTENT_BROWSER_OWNED_INTERFACE_H_ |
OLD | NEW |