Bug 577899, part 2: Add a DebugOnly helper to mfbt, which only contains a value in debug builds. r=luke
authorChris Jones <jones.chris.g@gmail.com>
Thu, 31 Mar 2011 20:46:35 -0500
changeset 64573 bfef135a83dcc6d9e2a1bf9697ff5ab5ddab0172
parent 64572 91a8d742c50969c39ff61709039f9670a9c5f9ce
child 64575 26463a06d0caf1355b5cdc729d93f22e04ccc053
push idunknown
push userunknown
push dateunknown
reviewersluke
bugs577899
milestone2.2a1pre
Bug 577899, part 2: Add a DebugOnly helper to mfbt, which only contains a value in debug builds. r=luke
mfbt/Util.h
--- a/mfbt/Util.h
+++ b/mfbt/Util.h
@@ -37,11 +37,56 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef mozilla_Util_h_
 #define mozilla_Util_h_
 
 namespace mozilla {
 
+/**
+ * DebugOnly contains a value of type T, but only in debug builds.  In
+ * release builds, it does not contain a value.  This helper is
+ * intended to be used along with ASSERT()-style macros, allowing one
+ * to write
+ *
+ *   DebugOnly<bool> check = Func();
+ *   ASSERT(check);
+ *
+ * more concisely than declaring |check| conditional on #ifdef DEBUG,
+ * but also without allocating storage space for |check| in release
+ * builds.
+ *
+ * DebugOnly instances can only be coerced to T in debug builds; in
+ * release builds, they don't have a value so type coercion is not
+ * well defined.
+ */
+template <typename T>
+struct DebugOnly
+{
+#ifdef DEBUG
+    T value;
+
+    DebugOnly() {}
+    DebugOnly(const T& other) : value(other) {}
+    DebugOnly& operator=(const T& rhs) {
+        value = rhs;
+        return *this;
+    }
+
+    operator T&() { return value; }
+    operator const T&() const { return value; }
+
+#else
+    DebugOnly() {}
+    DebugOnly(const T&) {}
+    DebugOnly& operator=(const T&) {}   
+#endif
+
+    // DebugOnly must always have a destructor or else it will
+    // generate "unused variable" warnings, exactly what it's intended
+    // to avoid!
+    ~DebugOnly() {}
+};
+
 } // namespace mozilla
 
 #endif  // mozilla_Util_h_