KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I'm trying to build a class template that packs a bunch of types in a suitably large char array, and allows access to the data as individual correctly typed references. Now, according to the standard this can lead to strict-aliasing violation, and hence undefined behavior, as we're accessing the char[] data via an object that is not compatible with it. Specifically, the standard states: If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined: the dynamic type of the object, a cv-qualified version of the dynamic type of the object, a type similar (as defined in 4.4) to the dynamic type of the object, a type that is the signed or unsigned type corresponding to the dynamic type of the object, a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object, an aggregate or union type that includes one of the aforementioned types among its elements or non-static data members (including, recursively, an element or non-static data member of a subaggregate or contained union), a type that is a (possibly cv-qualified) base class type of the dynamic type of the object, a char or unsigned char type. Given the wording of the highlighted bullet point, I came up with the following alias_cast idea: #include <iostream> #include <type_traits> template <typename T> T alias_cast(void *p) { typedef typename std::remove_reference<T>::type BaseType; union UT { BaseType t; }; return reinterpret_cast<UT*>(p)->t; } template <typename T, typename U> class Data { union { long align_; char data_[sizeof(T) + sizeof(U)]; }; public
Tags (comma-separated)
Save Edits
Cancel