. . , . , . , , .
Unions are a bit hacky because they make using objects more complicated. The compiler does not know how to create, destroy, or copy them, because many objects can use the same memory. Here is a small example of how I would do this if I would like to save memory (normal, an enumeration takes four bytes and is therefore inefficient for memory, but don't forget that;)
#include <cstdlib>
#include <iostream>
struct Vector
{
double x, y, z;
};
struct Element
{
enum Type { SCALAR, VECTOR };
Type type;
union {
double scalar;
Vector v;
} data;
};
int main(void)
{
Element vector_element;
vector_element.type = Element::VECTOR;
vector_element.data.v.x = 1;
vector_element.data.v.y = 2;
vector_element.data.v.z = 3;
Element scalar_element;
scalar_element.type = Element::SCALAR;
scalar_element.data.scalar = 3.142;
std::cout << "The size of type Element without enum would be: " << (sizeof(Element) - sizeof(Element::Type)) << " bytes." << std::endl;
return EXIT_SUCCESS;
}
By the way, for some strange reason, this results in 28 bytes. I expected 3 * 8 = 24 bytes.
source
share