fork download
  1. #include <iostream>
  2. #include <type_traits>
  3. using namespace std;
  4.  
  5. // Non-trivially-copyable type.
  6. struct NTC
  7. {
  8. int x;
  9. NTC(int mX) : x(mX) { }
  10. ~NTC() { cout << "boop." << x << endl; }
  11. };
  12.  
  13. int main()
  14. {
  15. using AS = aligned_storage_t<sizeof(NTC), alignof(NTC)>;
  16.  
  17. // Create two `std::aligned_storage` instances
  18. // and "fill" them with two "placement-new-constructed"
  19. // `NTC` instances.
  20. AS as1, as2;
  21. new (&as1) NTC{2};
  22. new (&as2) NTC{5};
  23.  
  24. // Swap the `aligned_storages`, not their contents.
  25. std::swap(as1, as2);
  26.  
  27. // Destroy the
  28. NTC& in1{*static_cast<NTC*>(static_cast<void*>(&as1))};
  29. NTC& in2{*static_cast<NTC*>(static_cast<void*>(&as2))};
  30. in1.~NTC();
  31. in2.~NTC();
  32.  
  33. return 0;
  34. }
Success #stdin #stdout 0s 3096KB
stdin
Standard input is empty
stdout
boop.5
boop.2