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