|
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
|
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ |
|
3 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
4 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
6 |
|
7 /* |
|
8 * Provides DebugOnly, a type for variables used only in debug builds (i.e. by |
|
9 * assertions). |
|
10 */ |
|
11 |
|
12 #ifndef mozilla_DebugOnly_h |
|
13 #define mozilla_DebugOnly_h |
|
14 |
|
15 namespace mozilla { |
|
16 |
|
17 /** |
|
18 * DebugOnly contains a value of type T, but only in debug builds. In release |
|
19 * builds, it does not contain a value. This helper is intended to be used with |
|
20 * MOZ_ASSERT()-style macros, allowing one to write: |
|
21 * |
|
22 * DebugOnly<bool> check = func(); |
|
23 * MOZ_ASSERT(check); |
|
24 * |
|
25 * more concisely than declaring |check| conditional on #ifdef DEBUG, but also |
|
26 * without allocating storage space for |check| in release builds. |
|
27 * |
|
28 * DebugOnly instances can only be coerced to T in debug builds. In release |
|
29 * builds they don't have a value, so type coercion is not well defined. |
|
30 * |
|
31 * Note that DebugOnly instances still take up one byte of space, plus padding, |
|
32 * when used as members of structs. |
|
33 */ |
|
34 template<typename T> |
|
35 class DebugOnly |
|
36 { |
|
37 public: |
|
38 #ifdef DEBUG |
|
39 T value; |
|
40 |
|
41 DebugOnly() { } |
|
42 DebugOnly(const T& other) : value(other) { } |
|
43 DebugOnly(const DebugOnly& other) : value(other.value) { } |
|
44 DebugOnly& operator=(const T& rhs) { |
|
45 value = rhs; |
|
46 return *this; |
|
47 } |
|
48 void operator++(int) { |
|
49 value++; |
|
50 } |
|
51 void operator--(int) { |
|
52 value--; |
|
53 } |
|
54 |
|
55 T* operator&() { return &value; } |
|
56 |
|
57 operator T&() { return value; } |
|
58 operator const T&() const { return value; } |
|
59 |
|
60 T& operator->() { return value; } |
|
61 const T& operator->() const { return value; } |
|
62 |
|
63 #else |
|
64 DebugOnly() { } |
|
65 DebugOnly(const T&) { } |
|
66 DebugOnly(const DebugOnly&) { } |
|
67 DebugOnly& operator=(const T&) { return *this; } |
|
68 void operator++(int) { } |
|
69 void operator--(int) { } |
|
70 #endif |
|
71 |
|
72 /* |
|
73 * DebugOnly must always have a destructor or else it will |
|
74 * generate "unused variable" warnings, exactly what it's intended |
|
75 * to avoid! |
|
76 */ |
|
77 ~DebugOnly() {} |
|
78 }; |
|
79 |
|
80 } |
|
81 |
|
82 #endif /* mozilla_DebugOnly_h */ |