Index: base/memory/ref_counted.h |
diff --git a/base/memory/ref_counted.h b/base/memory/ref_counted.h |
index b7cb5e064175466d747e5ae66125262d8f1558cf..e1d958d1a7960deecfdcbdcac4bf01d8dda39816 100644 |
--- a/base/memory/ref_counted.h |
+++ b/base/memory/ref_counted.h |
@@ -242,9 +242,30 @@ class scoped_refptr { |
} |
T* get() const { return ptr_; } |
- operator T*() const { return ptr_; } |
T* operator->() const { return ptr_; } |
+ // This operator allows a scoped_refptr to be safely evaluated as bool, using |
+ // the "Safe bool" idiom. By "safely", we mean that we are opening up as few |
+ // unsafe operations as possible. Simply using operator bool() can allow |
+ // silliness like: |
+ // int x = my_scoped_refptr; |
+ // return (my_scoped_refptr < 5); |
+ // See, e.g., http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Safe_bool |
+ // for more information on this idiom. |
+ typedef void (scoped_refptr<T>::*BoolType)() const; |
+ void this_type_does_not_support_comparisons() const {} |
+ operator BoolType() const { |
+ return ptr_ ? &scoped_refptr<T>::this_type_does_not_support_comparisons : |
+ NULL; |
+ } |
+ |
+ // Allow scoped_refptr<T> to be used in tree-based containers. Note that |
+ // operator< on pointers is technically implementation-defined, but it works |
+ // on all our platforms and is a common idiom in Chromium anyway. |
+ bool operator<(const scoped_refptr<T>& right) const { |
+ return ptr_ < right.ptr_; |
+ } |
+ |
// Release a pointer. |
// The return value is the current pointer held by this object. |
// If this object holds a NULL pointer, the return value is NULL. |