Last active
January 1, 2016 03:29
-
-
Save hatsusato/8086299 to your computer and use it in GitHub Desktop.
snipet of union in C++03 for KMC Advent Calendar 2013
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename T> | |
class BetterU { | |
bool is_allocated; | |
union { // 余分な構造体が必要ない | |
T i; | |
T* p; | |
}; | |
void Clean() { | |
if (IsAllocated()) { delete p; } | |
} | |
void Assign(T src) { | |
if (IsAllocated()) { | |
p = new T(src); | |
} else { | |
i = src; | |
} | |
} | |
public: | |
BetterU(T src, bool alloc) : is_allocated(alloc) { Assign(src); } | |
BetterU(const BetterU& src) : is_allocated(src.is_allocated) { Assign(src.GetValue()); } | |
BetterU& operator=(const BetterU& rhs) { | |
if (IsAllocated() && rhs.IsAllocated()) { | |
*p = *rhs.p; | |
} else { | |
Clean(); | |
is_allocated = rhs.IsAllocated(); | |
Assign(rhs.GetValue()); | |
} | |
return *this; | |
} | |
~BetterU() { Clean(); } | |
T GetValue() const { | |
if (IsAllocated()) { | |
return *p; | |
} else { | |
return i; | |
} | |
} | |
bool IsAllocated() const { return is_allocated; } | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment