Reviewers: ajwong,
Message:
I find it tedious to have to .get() any scoped_ptr variable that I want to
use
in a conditional statement, e.g.:
scoped_ptr<foo> x;
if (x.get()) { /* stuff */ }
With this patch, this is now legal:
scoped_ptr<foo> x;
if (x) { /* stuff */ }
Reference:
http://www.artima.com/cppsource/safebool.html
Description:
Allow scoped_ptr variables to be used in boolean expressions
BUG=none
Please review this at
https://codereview.chromium.org/11028044/
SVN Base: svn://
svn.chromium.org/chrome/trunk/src
Affected files:
M base/memory/scoped_ptr.h
Index: base/memory/scoped_ptr.h
diff --git a/base/memory/scoped_ptr.h b/base/memory/scoped_ptr.h
index
fab6c7e33f6546631d64b89719df2f8bada1e69c..44e20a5f29ae8815625727e24290faf348f66eaa
100644
--- a/base/memory/scoped_ptr.h
+++ b/base/memory/scoped_ptr.h
@@ -203,6 +203,11 @@ class scoped_ptr {
}
C* get() const { return ptr_; }
+ // Allow scoped_ptr<C> to be used in boolean expressions, but not
+ // implicitly convertable to a real bool (which is dangerous).
+ typedef C* scoped_ptr::*testable;
+ operator testable() const { return ptr_ ? &scoped_ptr::ptr_ : 0; }
+
// Comparison operators.
// These return whether two scoped_ptr refer to the same object, not
just to
// two different but equal objects.
@@ -328,6 +333,11 @@ class scoped_array {
return array_;
}
+ // Allow scoped_array<C> to be used in boolean expressions, but not
+ // implicitly convertable to a real bool (which is dangerous).
+ typedef C* scoped_array::*testable;
+ operator testable() const { return array_ ? &scoped_array::array_ : 0; }
+
// Comparison operators.
// These return whether two scoped_array refer to the same object, not
just to
// two different but equal objects.
@@ -451,6 +461,11 @@ class scoped_ptr_malloc {
return ptr_;
}
+ // Allow scoped_ptr_malloc<C> to be used in boolean expressions, but not
+ // implicitly convertable to a real bool (which is dangerous).
+ typedef C* scoped_ptr_malloc::*testable;
+ operator testable() const { return ptr_ ? &scoped_ptr_malloc::ptr_ : 0; }
+
// Comparison operators.
// These return whether a scoped_ptr_malloc and a plain pointer refer
// to the same object, not just to two different but equal objects.