Last active
January 1, 2016 03:59
-
-
Save hatsusato/8089365 to your computer and use it in GitHub Desktop.
snipet of union in C++11 for KMC Advent Calendar 2013
This file contains 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
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