fork download
  1. // file x.h
  2. struct X {
  3. int data;
  4. };
  5.  
  6.  
  7. // file y.h
  8. #include <cstddef>
  9. #include <type_traits>
  10.  
  11. class Y {
  12. public:
  13. Y();
  14. ~Y();
  15. /*...*/
  16. private:
  17. static const size_t sizeofx = 8;
  18. static const size_t alignofx = 4;
  19.  
  20. std::aligned_storage<sizeofx, alignofx>::type _x;
  21. };
  22.  
  23. // file y.cpp
  24. #include <new>
  25. //#include "y.h"
  26. //#include "x.h"
  27.  
  28. Y::Y() {
  29. // compile-time checks
  30. static_assert(sizeofx >= sizeof(X), "sizeofx too small");
  31. static_assert(alignofx == alignof(X), "alignofx is incorrect");
  32. // does not allocate memory, but constructs an object at &_x
  33. new (&_x) X;
  34. }
  35.  
  36. Y::~Y() {
  37. (reinterpret_cast<X*>(&_x))->~X();
  38. }
  39.  
  40.  
  41. // file main.cpp
  42. //#include "y.h"
  43.  
  44. int main()
  45. {
  46. Y y;
  47. return 0;
  48. }
Success #stdin #stdout 0s 3092KB
stdin
Standard input is empty
stdout
Standard output is empty