From dba2aef8ec72de5226a2d56d08d86b4c05e69f2f Mon Sep 17 00:00:00 2001 From: Axel Feldmann Date: Mon, 29 Apr 2019 11:15:58 -0400 Subject: [PATCH] slightly less undefined behavior in Vector3D and Vector4D implementations --- CMU462/include/CMU462/vector3D.h | 15 +++++++++++---- CMU462/include/CMU462/vector4D.h | 14 ++++++++++---- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/CMU462/include/CMU462/vector3D.h b/CMU462/include/CMU462/vector3D.h index 4f35f81..7fdec8e 100755 --- a/CMU462/include/CMU462/vector3D.h +++ b/CMU462/include/CMU462/vector3D.h @@ -5,6 +5,7 @@ #include #include +#include namespace CMU462 { @@ -14,8 +15,14 @@ namespace CMU462 { class Vector3D { public: - // components - double x, y, z; + /** + * this type-punning is still technically undefined behavior, but all major + * compilers explicitly define it (gcc, clang, msvc) + */ + union { + struct { double x; double y; double z; }; + std::array data; + }; /** * Constructor. @@ -43,12 +50,12 @@ class Vector3D { // returns reference to the specified component (0-based indexing: x, y, z) inline double& operator[] ( const int& index ) { - return ( &x )[ index ]; + return data[index]; } // returns const reference to the specified component (0-based indexing: x, y, z) inline const double& operator[] ( const int& index ) const { - return ( &x )[ index ]; + return data[index]; } inline bool operator==( const Vector3D& v) const { diff --git a/CMU462/include/CMU462/vector4D.h b/CMU462/include/CMU462/vector4D.h index 2492c26..b35fff8 100755 --- a/CMU462/include/CMU462/vector4D.h +++ b/CMU462/include/CMU462/vector4D.h @@ -15,8 +15,14 @@ namespace CMU462 { class Vector4D { public: - // components - double x, y, z, w; + /** + * this type-punning is still technically undefined behavior, but all major + * compilers explicitly define it (gcc, clang, msvc) + */ + union { + struct { double x; double y; double z; double w; }; + std::array data; + }; /** * Constructor. @@ -63,12 +69,12 @@ class Vector4D { // returns reference to the specified component (0-based indexing: x, y, z) inline double& operator[] ( const int& index ) { - return ( &x )[ index ]; + return data[ index ]; } // returns const reference to the specified component (0-based indexing: x, y, z) inline const double& operator[] ( const int& index ) const { - return ( &x )[ index ]; + return data[ index ]; } // negation