OLD | NEW |
(Empty) | |
| 1 // Copyright 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 SelfKeepAlive_h |
| 6 #define SelfKeepAlive_h |
| 7 |
| 8 #include "platform/heap/Persistent.h" |
| 9 #include "wtf/Allocator.h" |
| 10 #include "wtf/Assertions.h" |
| 11 |
| 12 namespace blink { |
| 13 |
| 14 // SelfKeepAlive<Object> is the idiom to use for objects that have to keep |
| 15 // themselves temporarily alive and cannot rely on there being some |
| 16 // external reference in that interval: |
| 17 // |
| 18 // class Opener { |
| 19 // public: |
| 20 // ... |
| 21 // void open() |
| 22 // { |
| 23 // // Retain a self-reference while in an open()ed state: |
| 24 // m_keepAlive = this; |
| 25 // .... |
| 26 // } |
| 27 // |
| 28 // void close() |
| 29 // { |
| 30 // // Clear self-reference that ensured we were kept alive while opened. |
| 31 // m_keepAlive.clear(); |
| 32 // .... |
| 33 // } |
| 34 // |
| 35 // private: |
| 36 // ... |
| 37 // SelfKeepAlive m_keepAlive; |
| 38 // }; |
| 39 // |
| 40 // The responsibility to call clear() in a timely fashion resides with the imple
mentation |
| 41 // of the object. |
| 42 // |
| 43 // |
| 44 template<typename Self> |
| 45 class SelfKeepAlive final { |
| 46 DISALLOW_NEW(); |
| 47 public: |
| 48 SelfKeepAlive() |
| 49 { |
| 50 } |
| 51 |
| 52 explicit SelfKeepAlive(Self* self) |
| 53 { |
| 54 assign(self); |
| 55 } |
| 56 |
| 57 SelfKeepAlive& operator=(Self* self) |
| 58 { |
| 59 assign(self); |
| 60 return *this; |
| 61 } |
| 62 |
| 63 void clear() |
| 64 { |
| 65 m_keepAlive.clear(); |
| 66 } |
| 67 |
| 68 explicit operator bool() const { return m_keepAlive; } |
| 69 |
| 70 private: |
| 71 void assign(Self* self) |
| 72 { |
| 73 ASSERT(!m_keepAlive || m_keepAlive.get() == self); |
| 74 m_keepAlive = self; |
| 75 } |
| 76 |
| 77 GC_PLUGIN_IGNORE("420515") |
| 78 Persistent<Self> m_keepAlive; |
| 79 }; |
| 80 |
| 81 } // namespace blink |
| 82 |
| 83 #endif // SelfKeepAlive_h |
OLD | NEW |