eigen/test/SafeScalar.h
Antonio Sanchez 8830d66c02 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.


(cherry picked from commit d213a0bcea2344aa3f6c9856da9f5b2a26ccec25)
2021-04-22 21:05:50 +00:00

31 lines
605 B
C++

// 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_;
};