1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/mfbt/DebugOnly.h Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,82 @@ 1.4 +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 1.5 +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ 1.6 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.8 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.9 + 1.10 +/* 1.11 + * Provides DebugOnly, a type for variables used only in debug builds (i.e. by 1.12 + * assertions). 1.13 + */ 1.14 + 1.15 +#ifndef mozilla_DebugOnly_h 1.16 +#define mozilla_DebugOnly_h 1.17 + 1.18 +namespace mozilla { 1.19 + 1.20 +/** 1.21 + * DebugOnly contains a value of type T, but only in debug builds. In release 1.22 + * builds, it does not contain a value. This helper is intended to be used with 1.23 + * MOZ_ASSERT()-style macros, allowing one to write: 1.24 + * 1.25 + * DebugOnly<bool> check = func(); 1.26 + * MOZ_ASSERT(check); 1.27 + * 1.28 + * more concisely than declaring |check| conditional on #ifdef DEBUG, but also 1.29 + * without allocating storage space for |check| in release builds. 1.30 + * 1.31 + * DebugOnly instances can only be coerced to T in debug builds. In release 1.32 + * builds they don't have a value, so type coercion is not well defined. 1.33 + * 1.34 + * Note that DebugOnly instances still take up one byte of space, plus padding, 1.35 + * when used as members of structs. 1.36 + */ 1.37 +template<typename T> 1.38 +class DebugOnly 1.39 +{ 1.40 + public: 1.41 +#ifdef DEBUG 1.42 + T value; 1.43 + 1.44 + DebugOnly() { } 1.45 + DebugOnly(const T& other) : value(other) { } 1.46 + DebugOnly(const DebugOnly& other) : value(other.value) { } 1.47 + DebugOnly& operator=(const T& rhs) { 1.48 + value = rhs; 1.49 + return *this; 1.50 + } 1.51 + void operator++(int) { 1.52 + value++; 1.53 + } 1.54 + void operator--(int) { 1.55 + value--; 1.56 + } 1.57 + 1.58 + T* operator&() { return &value; } 1.59 + 1.60 + operator T&() { return value; } 1.61 + operator const T&() const { return value; } 1.62 + 1.63 + T& operator->() { return value; } 1.64 + const T& operator->() const { return value; } 1.65 + 1.66 +#else 1.67 + DebugOnly() { } 1.68 + DebugOnly(const T&) { } 1.69 + DebugOnly(const DebugOnly&) { } 1.70 + DebugOnly& operator=(const T&) { return *this; } 1.71 + void operator++(int) { } 1.72 + void operator--(int) { } 1.73 +#endif 1.74 + 1.75 + /* 1.76 + * DebugOnly must always have a destructor or else it will 1.77 + * generate "unused variable" warnings, exactly what it's intended 1.78 + * to avoid! 1.79 + */ 1.80 + ~DebugOnly() {} 1.81 +}; 1.82 + 1.83 +} 1.84 + 1.85 +#endif /* mozilla_DebugOnly_h */