fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. union U {
  6. string s;
  7. int i;
  8. U (string s) : s(s) { cout << "s is active"<<endl;}
  9. U (int i) : i(i) { cout << "i is active"<<endl;}
  10. U() : s() { cout << "s is active by default" <<endl; }
  11. ~U() { cout << "delete... but what ?"<<endl; }
  12. };
  13.  
  14. int main() {
  15. U u("hello");
  16. u.s += ", world";
  17. cout << u.s <<endl;
  18.  
  19. u.s.~string(); // properly end the life of s
  20. u.i=0; // this is now the active member
  21. // no need to end life of an int, as it has a trivial destructor
  22. new (&u.s) string("goodbye"); // placement new
  23. cout << u.s <<endl;
  24. u.s.~string(); // because our destructor doesn't know what's active
  25.  
  26. return 0;
  27. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
s is active
hello, world
goodbye
delete... but what ?