Skip to content

Instantly share code, notes, and snippets.

@hatsusato
Last active January 1, 2016 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hatsusato/8086299 to your computer and use it in GitHub Desktop.
Save hatsusato/8086299 to your computer and use it in GitHub Desktop.
snipet of union in C++03 for KMC Advent Calendar 2013
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