I'm trying to use union (C ++), which has some non-primitive variables, but I'm stuck trying to create a destructor for this class. As I already read, it is impossible to guess which variable is used in the union, so there is no implicit destructor, and since I use this union on the stack, there are compiler errors that the destructor destroys. The union is as follows:
struct LuaVariant { LuaVariant() : type(VARIANT_NONE) { } LuaVariantType_t type; union { std::string text; Position pos; uint32_t number; }; };
The type
variable contains which union field is used (selected from the enumeration) for reading from the union, and it can be used to determine which value should be removed. I tried different approaches, but none of them worked. First of all, I just tried the default destructor:
~LuaVariant() = default;
This did not work because the default value ... was deleted. So, I tried to replace the value with an empty one, so that the contents were erased, and there would be no problem of "leak" of an empty value:
~LuaVariant() { switch (type) { case VARIANT_POSITION: case VARIANT_TARGETPOSITION: { Position p; std::swap(p, pos); break; } case VARIANT_STRING: { std::string s; std::swap(s, text); break; } default: number = 0; break; } };
But since I am not a master of trade unions, I donβt know if this can cause other problems, such as allocated memory that is never freed, or something like that. Is it possible to use this swap strategy without errors and problems?
source share