Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(390)

Side by Side Diff: base/memory/weak_ptr.h

Issue 2371663002: Introduce an injection point to configure the internal pointer of WeakPtr
Patch Set: fix Created 4 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | base/memory/weak_ptr_unittest.nc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 // Weak pointers are pointers to an object that do not affect its lifetime, 5 // Weak pointers are pointers to an object that do not affect its lifetime,
6 // and which may be invalidated (i.e. reset to nullptr) by the object, or its 6 // and which may be invalidated (i.e. reset to nullptr) by the object, or its
7 // owner, at any time, most commonly when the object is about to be deleted. 7 // owner, at any time, most commonly when the object is about to be deleted.
8 8
9 // Weak pointers are useful when an object needs to be accessed safely by one 9 // Weak pointers are useful when an object needs to be accessed safely by one
10 // or more objects other than its owner, and those callers can cope with the 10 // or more objects other than its owner, and those callers can cope with the
(...skipping 63 matching lines...) Expand 10 before | Expand all | Expand 10 after
74 #include <type_traits> 74 #include <type_traits>
75 75
76 #include "base/base_export.h" 76 #include "base/base_export.h"
77 #include "base/logging.h" 77 #include "base/logging.h"
78 #include "base/macros.h" 78 #include "base/macros.h"
79 #include "base/memory/ref_counted.h" 79 #include "base/memory/ref_counted.h"
80 #include "base/sequence_checker.h" 80 #include "base/sequence_checker.h"
81 81
82 namespace base { 82 namespace base {
83 83
84 template <typename T> class SupportsWeakPtr; 84 struct DefaultWeakPtrTraits {
85 template <typename T> class WeakPtr; 85 template <typename T>
86 struct PointerHolder {
87 protected:
88 PointerHolder(T* ptr) : ptr_(ptr) {}
89 void reset() { ptr_ = nullptr; }
90 T* get() const { return ptr_; }
91
92 private:
93 T* ptr_;
94 };
95
96 template <typename T>
97 using PointerType = T*;
98 };
99
100 template <typename T, typename Traits = DefaultWeakPtrTraits>
101 class SupportsWeakPtr;
102
103 template <typename T, typename Pointer = DefaultWeakPtrTraits>
104 class WeakPtr;
105
106 template <typename T, typename Pointer = DefaultWeakPtrTraits>
107 class WeakPtrFactory;
86 108
87 namespace internal { 109 namespace internal {
88 // These classes are part of the WeakPtr implementation. 110 // These classes are part of the WeakPtr implementation.
89 // DO NOT USE THESE CLASSES DIRECTLY YOURSELF. 111 // DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
90 112
91 class BASE_EXPORT WeakReference { 113 class BASE_EXPORT WeakReference {
92 public: 114 public:
93 // Although Flag is bound to a specific SequencedTaskRunner, it may be 115 // Although Flag is bound to a specific SequencedTaskRunner, it may be
94 // deleted from another via base::WeakPtr::~WeakPtr(). 116 // deleted from another via base::WeakPtr::~WeakPtr().
95 class BASE_EXPORT Flag : public RefCountedThreadSafe<Flag> { 117 class BASE_EXPORT Flag : public RefCountedThreadSafe<Flag> {
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after
157 protected: 179 protected:
158 explicit WeakPtrBase(const WeakReference& ref); 180 explicit WeakPtrBase(const WeakReference& ref);
159 181
160 WeakReference ref_; 182 WeakReference ref_;
161 }; 183 };
162 184
163 // This class provides a common implementation of common functions that would 185 // This class provides a common implementation of common functions that would
164 // otherwise get instantiated separately for each distinct instantiation of 186 // otherwise get instantiated separately for each distinct instantiation of
165 // SupportsWeakPtr<>. 187 // SupportsWeakPtr<>.
166 class SupportsWeakPtrBase { 188 class SupportsWeakPtrBase {
189 private:
190 // This template function uses type inference to find a Base of Derived
191 // which is an instance of SupportsWeakPtr<Base>. We can then safely
192 // static_cast the Base* to a Derived*.
193 template <typename Derived, typename Base, typename Traits>
194 static WeakPtr<Derived, Traits> AsWeakPtrImpl(
195 Derived* t,
196 const SupportsWeakPtr<Base, Traits>&) {
197 WeakPtr<Base, Traits> ptr = t->Base::AsWeakPtr();
198 return WeakPtr<Derived, Traits>(ptr.ref_, static_cast<Derived*>(ptr.get()));
199 }
200
167 public: 201 public:
168 // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This 202 // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
169 // conversion will only compile if there is exists a Base which inherits 203 // conversion will only compile if there is exists a Base which inherits
170 // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper 204 // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
171 // function that makes calling this easier. 205 // function that makes calling this easier.
172 template<typename Derived> 206 template <typename Derived>
173 static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) { 207 static auto StaticAsWeakPtr(Derived* t)
208 -> decltype(AsWeakPtrImpl<Derived>(t, *t)) {
174 static_assert( 209 static_assert(
175 std::is_base_of<internal::SupportsWeakPtrBase, Derived>::value, 210 std::is_base_of<internal::SupportsWeakPtrBase, Derived>::value,
176 "AsWeakPtr argument must inherit from SupportsWeakPtr"); 211 "AsWeakPtr argument must inherit from SupportsWeakPtr");
177 return AsWeakPtrImpl<Derived>(t, *t); 212 return AsWeakPtrImpl<Derived>(t, *t);
178 } 213 }
179
180 private:
181 // This template function uses type inference to find a Base of Derived
182 // which is an instance of SupportsWeakPtr<Base>. We can then safely
183 // static_cast the Base* to a Derived*.
184 template <typename Derived, typename Base>
185 static WeakPtr<Derived> AsWeakPtrImpl(
186 Derived* t, const SupportsWeakPtr<Base>&) {
187 WeakPtr<Base> ptr = t->Base::AsWeakPtr();
188 return WeakPtr<Derived>(ptr.ref_, static_cast<Derived*>(ptr.ptr_));
189 }
190 }; 214 };
191 215
192 } // namespace internal 216 } // namespace internal
193 217
194 template <typename T> class WeakPtrFactory;
195
196 // The WeakPtr class holds a weak reference to |T*|. 218 // The WeakPtr class holds a weak reference to |T*|.
197 // 219 //
198 // This class is designed to be used like a normal pointer. You should always 220 // This class is designed to be used like a normal pointer. You should always
199 // null-test an object of this class before using it or invoking a method that 221 // null-test an object of this class before using it or invoking a method that
200 // may result in the underlying object being destroyed. 222 // may result in the underlying object being destroyed.
201 // 223 //
202 // EXAMPLE: 224 // EXAMPLE:
203 // 225 //
204 // class Foo { ... }; 226 // class Foo { ... };
205 // WeakPtr<Foo> foo; 227 // WeakPtr<Foo> foo;
206 // if (foo) 228 // if (foo)
207 // foo->method(); 229 // foo->method();
208 // 230 //
209 template <typename T> 231 template <typename T, typename Traits>
210 class WeakPtr : public internal::WeakPtrBase { 232 class WeakPtr : public internal::WeakPtrBase,
233 public Traits::template PointerHolder<T> {
234 private:
235 using PointerHolder = typename Traits::template PointerHolder<T>;
236
211 public: 237 public:
212 WeakPtr() : ptr_(nullptr) {} 238 WeakPtr() : PointerHolder(nullptr) {}
213 239 WeakPtr(std::nullptr_t) : PointerHolder(nullptr) {}
214 WeakPtr(std::nullptr_t) : ptr_(nullptr) {}
215 240
216 // Allow conversion from U to T provided U "is a" T. Note that this 241 // Allow conversion from U to T provided U "is a" T. Note that this
217 // is separate from the (implicit) copy and move constructors. 242 // is separate from the (implicit) copy and move constructors.
218 template <typename U> 243 template <typename U, typename OtherTraits>
219 WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other), ptr_(other.ptr_) { 244 WeakPtr(const WeakPtr<U, OtherTraits>& other)
245 : WeakPtrBase(other), PointerHolder(other.get()) {}
246 template <typename U, typename OtherTraits>
247 WeakPtr(WeakPtr<U, OtherTraits>&& other)
248 : WeakPtrBase(std::move(other)), PointerHolder(other.get()) {}
249
250 T* get() const {
251 if (ref_.is_valid())
252 return PointerHolder::get();
253 return nullptr;
220 } 254 }
221 template <typename U>
222 WeakPtr(WeakPtr<U>&& other)
223 : WeakPtrBase(std::move(other)), ptr_(other.ptr_) {}
224
225 T* get() const { return ref_.is_valid() ? ptr_ : nullptr; }
226 255
227 T& operator*() const { 256 T& operator*() const {
228 DCHECK(get() != nullptr); 257 DCHECK(get() != nullptr);
229 return *get(); 258 return *get();
230 } 259 }
231 T* operator->() const { 260 T* operator->() const {
232 DCHECK(get() != nullptr); 261 DCHECK(get() != nullptr);
233 return get(); 262 return get();
234 } 263 }
235 264
236 void reset() { 265 void reset() {
237 ref_ = internal::WeakReference(); 266 ref_ = internal::WeakReference();
238 ptr_ = nullptr; 267 PointerHolder::reset();
239 } 268 }
240 269
241 // Allow conditionals to test validity, e.g. if (weak_ptr) {...}; 270 // Allow conditionals to test validity, e.g. if (weak_ptr) {...};
242 explicit operator bool() const { return get() != nullptr; } 271 explicit operator bool() const { return get() != nullptr; }
243 272
244 private: 273 private:
245 friend class internal::SupportsWeakPtrBase; 274 friend class internal::SupportsWeakPtrBase;
246 template <typename U> friend class WeakPtr; 275 template <typename, typename>
247 friend class SupportsWeakPtr<T>; 276 friend class WeakPtr;
248 friend class WeakPtrFactory<T>; 277 friend class SupportsWeakPtr<T, Traits>;
249 278 friend class WeakPtrFactory<T, Traits>;
250 WeakPtr(const internal::WeakReference& ref, T* ptr)
251 : WeakPtrBase(ref),
252 ptr_(ptr) {
253 }
254 279
255 // This pointer is only valid when ref_.is_valid() is true. Otherwise, its 280 // This pointer is only valid when ref_.is_valid() is true. Otherwise, its
256 // value is undefined (as opposed to nullptr). 281 // value is undefined (as opposed to nullptr).
257 T* ptr_; 282 WeakPtr(const internal::WeakReference& ref, T* ptr)
283 : WeakPtrBase(ref), PointerHolder(std::move(ptr)) {}
258 }; 284 };
259 285
260 // Allow callers to compare WeakPtrs against nullptr to test validity. 286 // Allow callers to compare WeakPtrs against nullptr to test validity.
261 template <class T> 287 template <typename T, typename Traits>
262 bool operator!=(const WeakPtr<T>& weak_ptr, std::nullptr_t) { 288 bool operator!=(const WeakPtr<T, Traits>& weak_ptr, std::nullptr_t) {
263 return !(weak_ptr == nullptr); 289 return !(weak_ptr == nullptr);
264 } 290 }
265 template <class T> 291 template <typename T, typename Traits>
266 bool operator!=(std::nullptr_t, const WeakPtr<T>& weak_ptr) { 292 bool operator!=(std::nullptr_t, const WeakPtr<T, Traits>& weak_ptr) {
267 return weak_ptr != nullptr; 293 return weak_ptr != nullptr;
268 } 294 }
269 template <class T> 295 template <typename T, typename Traits>
270 bool operator==(const WeakPtr<T>& weak_ptr, std::nullptr_t) { 296 bool operator==(const WeakPtr<T, Traits>& weak_ptr, std::nullptr_t) {
271 return weak_ptr.get() == nullptr; 297 return weak_ptr.get() == nullptr;
272 } 298 }
273 template <class T> 299 template <typename T, typename Traits>
274 bool operator==(std::nullptr_t, const WeakPtr<T>& weak_ptr) { 300 bool operator==(std::nullptr_t, const WeakPtr<T, Traits>& weak_ptr) {
275 return weak_ptr == nullptr; 301 return weak_ptr == nullptr;
276 } 302 }
277 303
278 // A class may be composed of a WeakPtrFactory and thereby 304 // A class may be composed of a WeakPtrFactory and thereby
279 // control how it exposes weak pointers to itself. This is helpful if you only 305 // control how it exposes weak pointers to itself. This is helpful if you only
280 // need weak pointers within the implementation of a class. This class is also 306 // need weak pointers within the implementation of a class. This class is also
281 // useful when working with primitive types. For example, you could have a 307 // useful when working with primitive types. For example, you could have a
282 // WeakPtrFactory<bool> that is used to pass around a weak reference to a bool. 308 // WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
283 template <class T> 309 template <typename T, typename Traits>
284 class WeakPtrFactory { 310 class WeakPtrFactory : public Traits::template PointerHolder<T> {
311 private:
312 using PointerHolder = typename Traits::template PointerHolder<T>;
313
285 public: 314 public:
286 explicit WeakPtrFactory(T* ptr) : ptr_(ptr) { 315 explicit WeakPtrFactory(T* ptr) : PointerHolder(ptr) {}
287 }
288 316
289 ~WeakPtrFactory() { ptr_ = nullptr; } 317 ~WeakPtrFactory() { PointerHolder::reset(); }
290 318
291 WeakPtr<T> GetWeakPtr() { 319 WeakPtr<T, Traits> GetWeakPtr() {
292 DCHECK(ptr_); 320 DCHECK(PointerHolder::get());
293 return WeakPtr<T>(weak_reference_owner_.GetRef(), ptr_); 321 return WeakPtr<T, Traits>(weak_reference_owner_.GetRef(),
322 PointerHolder::get());
294 } 323 }
295 324
296 // Call this method to invalidate all existing weak pointers. 325 // Call this method to invalidate all existing weak pointers.
297 void InvalidateWeakPtrs() { 326 void InvalidateWeakPtrs() {
298 DCHECK(ptr_); 327 DCHECK(PointerHolder::get());
299 weak_reference_owner_.Invalidate(); 328 weak_reference_owner_.Invalidate();
300 } 329 }
301 330
302 // Call this method to determine if any weak pointers exist. 331 // Call this method to determine if any weak pointers exist.
303 bool HasWeakPtrs() const { 332 bool HasWeakPtrs() const {
304 DCHECK(ptr_); 333 DCHECK(PointerHolder::get());
305 return weak_reference_owner_.HasRefs(); 334 return weak_reference_owner_.HasRefs();
306 } 335 }
307 336
308 private: 337 private:
309 internal::WeakReferenceOwner weak_reference_owner_; 338 internal::WeakReferenceOwner weak_reference_owner_;
310 T* ptr_;
311 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory); 339 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory);
312 }; 340 };
313 341
314 // A class may extend from SupportsWeakPtr to let others take weak pointers to 342 // A class may extend from SupportsWeakPtr to let others take weak pointers to
315 // it. This avoids the class itself implementing boilerplate to dispense weak 343 // it. This avoids the class itself implementing boilerplate to dispense weak
316 // pointers. However, since SupportsWeakPtr's destructor won't invalidate 344 // pointers. However, since SupportsWeakPtr's destructor won't invalidate
317 // weak pointers to the class until after the derived class' members have been 345 // weak pointers to the class until after the derived class' members have been
318 // destroyed, its use can lead to subtle use-after-destroy issues. 346 // destroyed, its use can lead to subtle use-after-destroy issues.
319 template <class T> 347 template <typename T, typename Traits>
320 class SupportsWeakPtr : public internal::SupportsWeakPtrBase { 348 class SupportsWeakPtr : public internal::SupportsWeakPtrBase {
321 public: 349 public:
322 SupportsWeakPtr() {} 350 SupportsWeakPtr() {}
323 351
324 WeakPtr<T> AsWeakPtr() { 352 WeakPtr<T, Traits> AsWeakPtr() {
325 return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this)); 353 return WeakPtr<T, Traits>(weak_reference_owner_.GetRef(),
354 static_cast<T*>(this));
326 } 355 }
327 356
328 protected: 357 protected:
329 ~SupportsWeakPtr() {} 358 ~SupportsWeakPtr() {}
330 359
331 private: 360 private:
332 internal::WeakReferenceOwner weak_reference_owner_; 361 internal::WeakReferenceOwner weak_reference_owner_;
333 DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr); 362 DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr);
334 }; 363 };
335 364
336 // Helper function that uses type deduction to safely return a WeakPtr<Derived> 365 // Helper function that uses type deduction to safely return a WeakPtr<Derived>
337 // when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it 366 // when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
338 // extends a Base that extends SupportsWeakPtr<Base>. 367 // extends a Base that extends SupportsWeakPtr<Base>.
339 // 368 //
340 // EXAMPLE: 369 // EXAMPLE:
341 // class Base : public base::SupportsWeakPtr<Producer> {}; 370 // class Base : public base::SupportsWeakPtr<Producer> {};
342 // class Derived : public Base {}; 371 // class Derived : public Base {};
343 // 372 //
344 // Derived derived; 373 // Derived derived;
345 // base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived); 374 // base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
346 // 375 //
347 // Note that the following doesn't work (invalid type conversion) since 376 // Note that the following doesn't work (invalid type conversion) since
348 // Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(), 377 // Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
349 // and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at 378 // and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
350 // the caller. 379 // the caller.
351 // 380 //
352 // base::WeakPtr<Derived> ptr = derived.AsWeakPtr(); // Fails. 381 // base::WeakPtr<Derived> ptr = derived.AsWeakPtr(); // Fails.
353 382
354 template <typename Derived> 383 template <typename Derived>
355 WeakPtr<Derived> AsWeakPtr(Derived* t) { 384 auto AsWeakPtr(Derived* t)
385 -> decltype(internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t)) {
356 return internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t); 386 return internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
357 } 387 }
358 388
359 } // namespace base 389 } // namespace base
360 390
361 #endif // BASE_MEMORY_WEAK_PTR_H_ 391 #endif // BASE_MEMORY_WEAK_PTR_H_
OLDNEW
« no previous file with comments | « no previous file | base/memory/weak_ptr_unittest.nc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698