aboutsummaryrefslogtreecommitdiffhomepage
path: root/test/SafeScalar.h
diff options
context:
space:
mode:
authorGravatar Antonio Sanchez <cantonios@google.com>2021-04-21 15:45:31 -0700
committerGravatar Rasmus Munk Larsen <rmlarsen@google.com>2021-04-22 18:45:19 +0000
commitd213a0bcea2344aa3f6c9856da9f5b2a26ccec25 (patch)
tree2cc3668db7d8928455a0e051d6373873ba4a316e /test/SafeScalar.h
parent85a76a16ea835fcfa7d4c185a338ae2aef9a272a (diff)
DenseStorage safely copy/swap.
Fixes #2229. For dynamic matrices with fixed-sized storage, only copy/swap elements that have been set. Otherwise, this leads to inefficient copying, and potential UB for non-initialized elements.
Diffstat (limited to 'test/SafeScalar.h')
-rw-r--r--test/SafeScalar.h30
1 files changed, 30 insertions, 0 deletions
diff --git a/test/SafeScalar.h b/test/SafeScalar.h
new file mode 100644
index 000000000..c5cb75717
--- /dev/null
+++ b/test/SafeScalar.h
@@ -0,0 +1,30 @@
+
+// A Scalar that asserts for uninitialized access.
+template<typename T>
+class SafeScalar {
+ public:
+ SafeScalar() : initialized_(false) {}
+ SafeScalar(const SafeScalar& other) {
+ *this = other;
+ }
+ SafeScalar& operator=(const SafeScalar& other) {
+ val_ = T(other);
+ initialized_ = true;
+ return *this;
+ }
+
+ SafeScalar(T val) : val_(val), initialized_(true) {}
+ SafeScalar& operator=(T val) {
+ val_ = val;
+ initialized_ = true;
+ }
+
+ operator T() const {
+ VERIFY(initialized_ && "Uninitialized access.");
+ return val_;
+ }
+
+ private:
+ T val_;
+ bool initialized_;
+};