Skip to content

Instantly share code, notes, and snippets.

@hatsusato
Last active January 1, 2016 03:59
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/8089365 to your computer and use it in GitHub Desktop.
Save hatsusato/8089365 to your computer and use it in GitHub Desktop.
snipet of union in C++11 for KMC Advent Calendar 2013
union Safe {
Safe(const char* src) : s{src} {}
~Safe() { s.~basic_string(); }
unsigned long long ull{0ULL}; // クラス内初期化は1つまで
std::string s;
};
union Danger {
Danger(const char* src) : s{src} {}
~Danger() { s.~basic_string(); }
std::string s;
unsigned long long ull{0ULL}; // 逆順にした場合
};
int main() {
Safe safe{"abc"};
Danger danger{"abc"};
std::cout << safe.ull << std::endl; // ポインタ値が見えるはず
std::cout << danger.ull << std::endl; // 0 になっているはず
return 0;
// Segmentation fault
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment