I wrote a custom optional class (since I am forced to use C++98 without STL). It looks like this:
template <typename T>
struct optional {
char value[sizeof(T)];
bool has_value;
T& operator*() {
return *reinterpret_cast<T*>(value);
}
};
The compiler produces the warning dereferencing type-punned pointer will break strict aliasing rules
.
What can I do to make this class without UB?
Maybe memcpy
should be used, but I don't understand how.
What can I do to make this class without UB?
optional
It would be much easier to allocate the object dynamically. Slower, very likely. But simpler and standard conformant.