From d213a0bcea2344aa3f6c9856da9f5b2a26ccec25 Mon Sep 17 00:00:00 2001 From: Antonio Sanchez Date: Wed, 21 Apr 2021 15:45:31 -0700 Subject: 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. --- test/SafeScalar.h | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 test/SafeScalar.h (limited to 'test/SafeScalar.h') 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 +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_; +}; -- cgit v1.2.3